package com.joysuch.wwyt.risk.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.joysuch.wwyt.bp.entity.BpDepart;
import com.joysuch.wwyt.bp.entity.BpJob;
import com.joysuch.wwyt.bp.entity.bean.BpRecordItemBean;
import com.joysuch.wwyt.bp.entity.investigate.BpInvestigatePlan;
import com.joysuch.wwyt.bp.entity.investigate.BpInvestigateType;
import com.joysuch.wwyt.bp.enums.DataStateTypes;
import com.joysuch.wwyt.bp.enums.PlanCheckRateType;
import com.joysuch.wwyt.bp.enums.PlanStatus;
import com.joysuch.wwyt.bp.enums.SourceType;
import com.joysuch.wwyt.bp.repository.BpDepartDao;
import com.joysuch.wwyt.bp.repository.BpInvestigatePlanRepository;
import com.joysuch.wwyt.bp.repository.BpInvestigateRecordItemDao;
import com.joysuch.wwyt.bp.repository.BpJobDao;
import com.joysuch.wwyt.bp.service.BpDepartService;
import com.joysuch.wwyt.bp.service.BpInvestigatePlanService;
import com.joysuch.wwyt.bp.service.BpInvestigateTypeService;
import com.joysuch.wwyt.common.constant.Constant;
import com.joysuch.wwyt.core.bean.SimpleListBean;
import com.joysuch.wwyt.core.bean.SimpleSelectListBean;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.common.util.DateTimeUtil;
import com.joysuch.wwyt.core.common.util.PageDataUtils;
import com.joysuch.wwyt.core.common.util.SimpleDateFormatCache;
import com.joysuch.wwyt.core.constant.Constants;
import com.joysuch.wwyt.core.entity.BaseTypeGroup;
import com.joysuch.wwyt.core.entity.BaseTypeGroupItem;
import com.joysuch.wwyt.core.entity.BaseUser;
import com.joysuch.wwyt.core.enums.BaseConfigCodes;
import com.joysuch.wwyt.core.enums.DeleteFlag;
import com.joysuch.wwyt.core.enums.RiskLevels;
import com.joysuch.wwyt.core.enums.Status;
import com.joysuch.wwyt.core.exception.ApiBusinessException;
import com.joysuch.wwyt.core.exception.BusinessRestrictionsException;
import com.joysuch.wwyt.core.repository.BaseTypeGroupDao;
import com.joysuch.wwyt.core.repository.BaseTypeGroupItemDao;
import com.joysuch.wwyt.core.repository.BaseUserDao;
import com.joysuch.wwyt.core.service.BaseRoleDataAuthService;
import com.joysuch.wwyt.core.support.Context;
import com.joysuch.wwyt.mh.service.MonitorPointDataWebSocketService;
import com.joysuch.wwyt.risk.bean.*;
import com.joysuch.wwyt.risk.entity.*;
import com.joysuch.wwyt.risk.entity.dsl.QRiskDistrict;
import com.joysuch.wwyt.risk.entity.dto.*;
import com.joysuch.wwyt.risk.entity.vo.RiskEvaluationRecordDeleteCheckVO;
import com.joysuch.wwyt.risk.entity.vo.RiskItemEvalCountRecordVo;
import com.joysuch.wwyt.risk.entity.vo.RiskMeasureTypeNode;
import com.joysuch.wwyt.risk.enums.*;
import com.joysuch.wwyt.risk.mapper.RiskControllevelsMapper;
import com.joysuch.wwyt.risk.mapper.RiskDynamicRecordMapper;
import com.joysuch.wwyt.risk.mapper.RiskPointMapper;
import com.joysuch.wwyt.risk.repository.*;
import com.joysuch.wwyt.risk.service.*;
import com.joysuch.wwyt.util.PageableUtil;
import com.joysuch.wwyt.util.StringUtil;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.BooleanExpression;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class RiskEvaluationBusinessServiceImpl implements RiskEvaluationBusinessService {

    @Autowired
    private RiskStableEvalutionService riskStableEvalutionService;

    @Autowired
    private RiskEvaluationControlDao riskEvaluationControlDao;
    @Autowired
    private RiskEvaluationCorrectionRuleDao correctionRuleDao;
    @Autowired
    private RiskEvaluationAnalyzeWayDao analyzeWayDao;
    @Autowired
    private RiskEvaluationAnalyzeMethodDao analyzeMethodDao;
    @Autowired
    private RiskEvaluationTargetItemDao targetItemDao;
    @Autowired
    private RiskEvaluationBusinessDao businessDao;
    @Autowired
    private BpDepartDao bpDepartDao;
    @Autowired
    private BaseUserDao baseUserDao;
    @Autowired
    private RiskDistrictDao riskDistrictDao;
    @Autowired
    private RiskPointEvaluationBusinessDao pointEvaluationBusinessDao;
    @Autowired
    private RiskPointEvaluationItemDao riskPointEvaluationItemDao;
    @Autowired
    private RiskPointEvaluationDetailDao riskPointEvaluationDetailDao;
    @Autowired
    private RiskPointTypeDao riskPointTypeDao;
    @Autowired
    private RiskPointDao riskPointDao;
    @Autowired
    private BaseTypeGroupDao baseTypeGroupDao;
    @Autowired
    private BaseTypeGroupItemDao baseTypeGroupItemDao;
    @Autowired
    private RiskEvaluationAlarmMesageService evaluationAlarmMessageService;
    @Autowired
    private RiskEvaluationPlanService riskEvaluationPlanService;
    @Autowired
    private RiskPointMapper riskPointMapper;
    @Autowired
    private BaseRoleDataAuthService dataAuthService;
    @Autowired
    private RiskControlLevelService riskControllevelsService;
    @Autowired
    RiskMeasureTypeService riskMeasureTypeService;
    @Autowired
    RiskHiddenDangerContentService riskHiddenDangerContentService;
    @Autowired
    private BpJobDao bpJobDao;
    @Autowired
    RiskControllevelsMapper riskControllevelsMapper;

    @Autowired
    private BpInvestigatePlanService bpInvestigatePlanService;
    @Autowired
    private BpInvestigatePlanRepository bpInvestigatePlanRepository;
    @Autowired
    private RiskPointEvaluationBusinessDao riskPointEvaluationBusinessDao;
    @Autowired
    private BpInvestigateRecordItemDao bpInvestigateRecordItemDao;
    @Autowired
    private BpInvestigateTypeService bpInvestigateTypeService;
    @Autowired
    private RiskItemEvalCountRecordService riskItemEvalCountRecordService;
    @Autowired
    private RiskDynamicRecordMapper riskDynamicRecordMapper;
    @Autowired
    private RiskDynamicConfigDao riskDynamicConfigDao;
    @Autowired
    private MonitorPointDataWebSocketService monitorPointDataWebSocketService;
    @Autowired
    private RiskEvaluationControlService riskEvaluationControlService;

    @Autowired
    private BpDepartService departService;


    /**
     * 获取风险分区评估列表
     *
     * @param page
     * @param condition
     * @return
     */
    @Override
    public Page<RiskEvaluationBusinessPageBean> pageRiskDistrictEvaluation(Pageable page, RiskDistrictStableRiskListSearchBean condition) {
        QRiskDistrict point = QRiskDistrict.riskDistrict;
        Predicate predicate = null;
        if (condition.getNameOrCode() != null) {
            predicate = ExpressionUtils.or(point.name.like("%" + condition.getNameOrCode() + "%"),
                    point.code.like("%" + condition.getNameOrCode() + "%"));
        }
        if (condition.getState() != null && condition.getState() == 1) {
            BooleanExpression eq = point.evaluationState.eq(condition.getState());
            predicate = predicate == null ? eq : ExpressionUtils.and(predicate, eq);
        }
        //未评估
        if (condition.getState() != null && condition.getState() == 0) {
            BooleanExpression eq = point.evaluationState.isNull();
            predicate = predicate == null ? eq : ExpressionUtils.and(predicate, eq);
        }
        if (condition.getRiskLevel() != null) {
            BooleanExpression eq = point.riskLevel.eq(condition.getRiskLevel());
            predicate = predicate == null ? eq : ExpressionUtils.and(predicate, eq);
        }
        if (condition.getDepartId() != null) {
            BooleanExpression eq = point.responsibleDept.eq(condition.getDepartId());
            predicate = predicate == null ? eq : ExpressionUtils.and(predicate, eq);
        }
        predicate = ExpressionUtils.and(predicate, ExpressionUtils.or(point.state.notIn(DataStateTypes.DELETE.getState()), point.state.isNull()));
        //
        Page<RiskDistrict> all = predicate == null ? riskDistrictDao.findAll(page) : riskDistrictDao.findAll(predicate, page);
        return PageDataUtils.convertPageData(all, new PageDataUtils.PageDataConvert<RiskEvaluationBusinessPageBean, RiskDistrict>() {

            @Override
            public RiskEvaluationBusinessPageBean convert(RiskDistrict f) {
                RiskEvaluationBusinessPageBean bean = new RiskEvaluationBusinessPageBean();
                bean.setId(f.getId());
                bean.setCode(f.getCode());
                bean.setName(f.getName());
                RiskEvaluationBusiness evaluationBusiness = businessDao.findByRiskDistrictId(f.getId());
                Date date = null;
                Date disDate = null;
                Date evalDate = riskPointEvaluationBusinessDao.getLastEvalDateByDistrictId(f.getId());
                if (evaluationBusiness != null) {
                    bean.setEvaluationId(evaluationBusiness.getId());
                    disDate = evaluationBusiness.getEvaluationDate();
                }
                bean.setResponsibleDepartId(f.getResponsibleDept());
                bean.setResponsibleDepartName(getDepartName(f.getResponsibleDept()));
                //区域固有风险
                bean.setStableRiskLevel(f.getStableRiskLevel());
                bean.setStableRiskLevelName(RiskLevels.findRiskLevelName(f.getStableRiskLevel()));
                //区域风险
                bean.setRiskLevel(f.getRiskLevel());
                bean.setRiskLevelName(RiskLevels.findRiskLevelName(f.getRiskLevel()));
                bean.setState(f.getEvaluationState());
                if (evalDate != null && disDate != null) {
                    if (evalDate.before(disDate)) {
                        date = disDate;
                    } else {
                        date = evalDate;
                    }
                } else if (evalDate != null && disDate == null) {
                    date = evalDate;
                } else if (evalDate == null && disDate != null) {
                    date = disDate;
                }
                bean.setEvaluationYear(date);
                return bean;
            }

        });
    }

    /**
     * 保存风险评估
     *
     * @param bean
     * @return
     */
    @Override
    public RiskEvaluationBusiness saveBusiness(RiskEvaluationBusinessBean bean) {
        RiskDistrict district = riskDistrictDao.findById(bean.getRiskDistrictId()).orElseThrow(() -> new IllegalArgumentException("风险区域不存在"));
        bean.setEvaluationDate(getNowDate());
        RiskEvaluationBusiness eb = new RiskEvaluationBusiness();
        if (bean.getId() != null) {
            eb = businessDao.findById(bean.getId()).orElseThrow(() -> new IllegalArgumentException("风险评估不存在"));
        }
        //风险区域id
        eb.setRiskDistrictId(bean.getRiskDistrictId());
        //区域风险等级
        eb.setRiskLevel(bean.getRiskLevel());
        //责任人id
        eb.setResponsibleUserId(bean.getResponsibleUserId());
        //责任单位id
        eb.setResponsibleDepartId(bean.getResponsibleDepartId());
        // 查询当前配置开关
        RiskEvaluationControl districtRuleSwitch = riskEvaluationControlDao.findByName("区域风险等级校正");
        RiskEvaluationControl districtStableSwitch = riskEvaluationControlDao.findByName("区域固有风险评价");
        if (districtRuleSwitch != null && districtRuleSwitch.getSwitchState() != null && districtRuleSwitch.getSwitchState().intValue() == 1) {
            //等级校正选项
            List<Long> ruleIdJson = bean.getRuleIdJson();
            if (bean.getRuleIdJson() == null) {
                ruleIdJson = Lists.newArrayList();
            }
            eb.setRuleIdJson(JSONArray.toJSONString(ruleIdJson));
        } else if (districtRuleSwitch != null && districtRuleSwitch.getSwitchState() != null && districtRuleSwitch.getSwitchState().intValue() == 0) {
            eb.setRuleIdJson(null);
        }
        Integer stableLevel = district.getStableRiskLevel();
        if (districtStableSwitch != null && districtStableSwitch.getSwitchState() != null && districtStableSwitch.getSwitchState().intValue() == 1) {
            RiskStableEvalution riskStableEvalution = bean.getRiskStableEvalution();
            if (riskStableEvalution != null) {
                RiskStableEvalution stableEvalution = null;
                if (riskStableEvalution.getId() != null) {
                    stableEvalution = riskStableEvalutionService.update(riskStableEvalution);
                } else {
                    stableEvalution = riskStableEvalutionService.add(riskStableEvalution);
                }
                eb.setStableId(stableEvalution.getId());
            }
            //评估人id集合
            if (!CollectionUtils.isEmpty(bean.getEvaluationUserIds())) {
                eb.setEvaluationUserIds(JSONArray.toJSONString(bean.getEvaluationUserIds()));
            } else {
                eb.setEvaluationUserIds(null);
            }
            //评估单位id
            eb.setEvaluationDepartId(bean.getEvaluationDepartId());
            //评估日期
            eb.setEvaluationDate(bean.getEvaluationDate());
            eb.setStableRiskLevel(bean.getStableRiskLevel());
            stableLevel = bean.getStableRiskLevel();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(bean.getEvaluationDate());
            int year = calendar.get(Calendar.YEAR);
            district.setLastEvaluationYear(year);
            district.setNextEvaluationDate(add6Month(bean.getEvaluationDate()));
        } else if (districtStableSwitch != null && districtStableSwitch.getSwitchState() != null && districtStableSwitch.getSwitchState().intValue() == 0) {
            eb.setStableId(null);
            eb.setEvaluationUserIds(null);
            eb.setEvaluationDepartId(null);
            eb.setEvaluationDate(null);
            eb.setStableRiskLevel(district.getStableRiskLevel());
        }

        RiskEvaluationBusiness save = businessDao.save(eb);
        //更新风险区域
        Integer oldLevel = null;
        oldLevel = district.getRiskLevel();
        district.setRiskLevel(save.getRiskLevel());
        district.setStableRiskLevel(stableLevel);
        district.setEvaluationState(1);
        district = riskDistrictDao.save(district);
        //更新区域风险评估计划
        riskEvaluationPlanService.districtReCal(district, bean.getEvaluationDate(), 1);
        editDistrictLevel(riskDistrictDao.findById(save.getRiskDistrictId()).get(), oldLevel, "区域风险评估");
        return save;
    }

//    private int getAlarmSwitchFlag(String orgCode, Long tenentId) {
//        //flag 1->评估报警  2->实时报警  3->动态报警
//        int flag = 0;
//        RiskEvaluationControl riskCo = riskEvaluationControlDao.findByNameAndOrgCodeAndTenentId("风险四色图计算逻辑", orgCode.substring(0, 7), tenentId);
//        if (riskCo.getSwitchState() == 0) {
//            flag = 1;
//        } else {
//            flag = 2;
//        }
//        return flag;
//    }

    /**
     * 获取风险评估
     *
     * @param riskDistrictId
     * @return
     */
    @Override
    public RiskEvaluationBusinessShowBean getBusinessById(Long riskDistrictId) {
        RiskEvaluationBusinessShowBean bean = new RiskEvaluationBusinessShowBean();
        RiskDistrict district = riskDistrictDao.findById(riskDistrictId).orElseThrow(() -> new IllegalArgumentException("风险区域不存在"));
        bean.setRiskDistrictId(district.getId());
        bean.setRiskDistrictName(district.getName());
        bean.setRiskDistrictCode(district.getCode());
        bean.setRiskLevel(district.getRiskLevel());
        bean.setRiskLevelName(RiskLevels.findRiskLevelName(district.getRiskLevel()));
        //责任人
        if (StringUtils.isNotBlank(district.getResponsibleUser())) {
            List<Long> userIds = JSONArray.parseArray(district.getResponsibleUser(), Long.class);
            List<SimpleListBean> repUserBeanList = new ArrayList<>();
            for (Long userId : userIds) {
                SimpleListBean slBean = new SimpleListBean();
                Optional<BaseUser> obu = baseUserDao.findById(userId);
                if (obu.isPresent()) {
                    slBean.setName(obu.get().getRealName());
                }
                slBean.setId(userId);
                repUserBeanList.add(slBean);
            }
            bean.setResponsibleUseBeanList(repUserBeanList);
        }
        //责任单位
        bean.setResponsibleDepartId(district.getResponsibleDept());
        if (district.getResponsibleDept() != null) {
            Optional<BpDepart> obd = bpDepartDao.findById(district.getResponsibleDept());
            if (obd.isPresent()) {
                bean.setResponsibleDepartName(obd.get().getName());
            }
        }
        RiskEvaluationBusiness bus = businessDao.findByRiskDistrictId(riskDistrictId);
        Date date = null;
        Date disDate = null;
        Date evalDate = riskPointEvaluationBusinessDao.getLastEvalDateByDistrictId(riskDistrictId);
        if (bus != null) {
            disDate = bus.getEvaluationDate();
        }
        //区域固有评估日期
        bean.setEvaluationDate(disDate);
        boolean pointEvalFlag = false;
        RiskEvaluationControl stableCont = riskEvaluationControlDao.findByName("区域固有风险评价");
        if (evalDate != null) {
            pointEvalFlag = true;
        } else {

            if (stableCont != null && stableCont.getSwitchState().intValue() == 1 && district.getStableRiskLevel() != null) {
                pointEvalFlag = true;
            }
        }
        bean.setPointEvalFlag(pointEvalFlag);
        if (evalDate != null && disDate != null) {
            if (evalDate.before(disDate)) {
                date = disDate;
            } else {
                date = evalDate;
            }
        } else if (evalDate != null && disDate == null) {
            date = evalDate;
        } else if (evalDate == null && disDate != null) {
            date = disDate;
        }
        //区域评估日期
        bean.setDistrictEvaluationDate(date);
        bean.setStableRiskLevel(district.getStableRiskLevel());
        bean.setStableRiskLevelName(RiskLevels.findRiskLevelName(district.getStableRiskLevel()));
        if (bus == null) {
            RiskStableEvalutionBean riskStableEvalutionBean = new RiskStableEvalutionBean();
            riskStableEvalutionBean.setRiskLevel(district.getStableRiskLevel());
            bean.setRiskStableEvalutionBean(riskStableEvalutionBean);
            return bean;
        }
        bean.setId(bus.getId());
        SimpleListBean departBean = this.getv2DepartName(bus.getResponsibleDepartId());
        if (stableCont.getSwitchState() != null && stableCont.getSwitchState() == 1) {
            //风险区域固有评估
            RiskStableEvalutionBean stableEvalutionBean = new RiskStableEvalutionBean();
            if (bus.getStableId() != null) {
                RiskStableEvalution evalution = new RiskStableEvalution();
                evalution.setId(bus.getStableId());
                stableEvalutionBean = riskStableEvalutionService.findOne(evalution);
            }
            stableEvalutionBean.setRiskLevel(district.getStableRiskLevel());
            bean.setRiskStableEvalutionBean(stableEvalutionBean);
            //评估单位
            SimpleListBean dpBean = this.getv2DepartName(bus.getEvaluationDepartId());
            bean.setEvaluationDepartId(dpBean.getId());
            bean.setEvaluationDepartName(dpBean.getName());
            //评估人
            if (StringUtils.isNotBlank(bus.getEvaluationUserIds())) {
                List<Long> evaluationUserIds = StringUtil.covertJsonToLongList(bus.getEvaluationUserIds());
                bean.setEvaluationUserIds(evaluationUserIds);
                List<SimpleListBean> evaluationUserBeanList = getEvaluationUserBean(evaluationUserIds);
                if (!CollectionUtils.isEmpty(evaluationUserBeanList)) {
                    bean.setEvaluationUserBeanList(evaluationUserBeanList);
                }
            }
        }
        RiskEvaluationControl ruleCont = riskEvaluationControlDao.findByName("区域风险等级校正");
        if (ruleCont.getSwitchState() != null && ruleCont.getSwitchState().intValue() == 1) {
            //顶级校正
            String ruleIdJson = bus.getRuleIdJson();
            if (StringUtils.isNotBlank(ruleIdJson)) {
                List<Long> array = JSON.parseArray(ruleIdJson, Long.class);
                Iterator<Long> iterator = array.iterator();
                if (iterator.hasNext()) {
                    Optional<RiskEvaluationCorrectionRule> byId = correctionRuleDao.findById(iterator.next());
                    if (!byId.isPresent()) {
                        iterator.remove();
                    }
                }
                bean.setRuleIdJson(array);
            }
        }
        return bean;
    }

    private List<SimpleListBean> getEvaluationUserBean(List<Long> userIds) {
        List<SimpleListBean> beanList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(userIds)) {
            for (Long userId : userIds) {
                if (userId != null) {
                    SimpleListBean bean = new SimpleListBean();
                    String userName = getUserName(userId);
                    bean.setName(userName);
                    bean.setId(userId);
                    beanList.add(bean);
                }
            }

        }
        return beanList;
    }

    /**
     * 新增风险点控制风险评估
     * 当作业票绑定评估时 传评估id获取特定的评估内容 否则不传获取获最近一次评估
     *
     * @param bean
     * @return
     */
    @Override
    public RiskPointEvaluationBusiness savePointEvaluation(RiskPointEvaluationBusinessBean bean) {
        if (bean.getEvaluationDate() == null) {
            bean.setEvaluationDate(new Date());
        }
        //refEval 为空或者等于0 新增
        Integer refEval = bean.getRefEval();
        if (refEval == null || refEval.equals(0)) {
            bean.setPointBusinessId(null);
        }

        RiskPointEvaluationBusiness business = new RiskPointEvaluationBusiness();
        if (bean.getPointBusinessId() != null) {
            business = pointEvaluationBusinessDao.findById(bean.getPointBusinessId()).orElseThrow(() -> new IllegalArgumentException("风险评估不存在"));
        }

        RiskPoint riskPoint = riskPointDao.findById(bean.getPointId()).orElseThrow(() -> new IllegalArgumentException("风险点不存在"));
        Integer shared = riskPoint.getShared();
        //保存风险点评估(固有风险/控制风险) 风险点库 控制风险评估
        BeanUtils.copyProperties(bean, business);
        //固有风险配置
        RiskEvaluationControl control = riskEvaluationControlDao.findByName(BaseConfigCodes.WWYT_RISK_NAME);
        // 查询当前配置开关
        if (bean.getPointAnalyzeType() != null && bean.getPointAnalyzeType().intValue() == 0) {
            if (control.getSwitchState() != null && control.getSwitchState().intValue() == 0) {
                throw new IllegalArgumentException("当前风险单元固有风险评估开关已关闭");
            }
        }
        //风险点类别:null风险点;1风险点库
        business.setShared(shared);
        if (!CollectionUtils.isEmpty(bean.getEvaluationUserIds())) {
            business.setEvaluationUserIds(JSONArray.toJSONString(bean.getEvaluationUserIds()));
        }
        RiskPointEvaluationBusiness pointBusiness = pointEvaluationBusinessDao.save(business);
        //风险点评估值
        String pointEvaluationValue = null;
        //风险辨识评估
        if (!CollectionUtils.isEmpty(bean.getDeleteItemIds())) {
            riskPointEvaluationItemDao.deleteAllByIds(bean.getDeleteItemIds());
            riskPointEvaluationDetailDao.deleteByItemIds(bean.getDeleteItemIds());
        }
        if (!CollectionUtils.isEmpty(bean.getDeleteDetailIds())) {
            riskPointEvaluationDetailDao.deleteByIds(bean.getDeleteDetailIds());
        }
        List<RiskPointEvaluationItemAddBean> itemList = bean.getItemList();
        List<RiskPointEvaluationDetail> details = new ArrayList<>();
        if (!CollectionUtils.isEmpty(itemList)) {
            int orderNumber = 1;
            for (RiskPointEvaluationItemAddBean itemAddBean : itemList) {
                //序号 item
                itemAddBean.setOrderNumber(orderNumber++);
                RiskPointEvaluationItem pointItem = covertPointEvaluationItem(itemAddBean, bean, pointBusiness.getId(), shared, bean.getPointAnalyzeType());
                pointItem = riskPointEvaluationItemDao.save(pointItem);
                List<RiskPointEvaluationDetailAddBean> detailList = itemAddBean.getDetailList();
                if (!CollectionUtils.isEmpty(detailList)) {
                    for (RiskPointEvaluationDetailAddBean detailAddBean : detailList) {
                        //详情
                        RiskPointEvaluationDetail detail = covertEvaluationDetail(shared, detailAddBean, bean, pointBusiness.getId(), pointItem.getId(), pointEvaluationValue);
                        details.add(detail);
                    }
                }
            }
            if (!CollectionUtils.isEmpty(details)) {
                riskPointEvaluationDetailDao.saveAll(details);
            }
        }
        //更新风险点 风险区域 风险区域评估等级
        Integer oldLevel = null;
        RiskPoint point = riskPointDao.findById(pointBusiness.getPointId()).orElseThrow(() -> new IllegalArgumentException("风险点不存在"));
        if (point.getRiskDistrict() != null) {
            oldLevel = point.getRiskDistrict().getRiskLevel();
        }
        //修改风险点内容
        point = editPointData(bean, point, pointEvaluationValue, pointBusiness.getAnalyzeWayId());
        if (shared == null || shared.equals(0)) {
            //更改风险点评估计划
            riskEvaluationPlanService.riskPointReCal(point, bean.getEvaluationDate(), 1);
            if (point.getRiskDistrict() != null) {
                point.getRiskDistrict().setEvaluationState(1);
                editDistrictLevel(point.getRiskDistrict(), oldLevel, "区域风险评估");
            }
        }
        return business;
    }

    /**
     * 新增风险点控制风险评估
     *
     * @param bean
     * @return
     */
    @Override
    public RiskPointEvaluationBusiness savePointEvaluationForAssessment(RiskPointEvaluationBusinessBean bean) throws BusinessRestrictionsException {
        if (bean.getEvaluationDate() == null) {
            bean.setEvaluationDate(new Date());
        }
        List<RiskPointEvaluationItemAddBean> itemList = bean.getItemList();
        List<RiskPointStableDetailBean> stableDetailList = null;

        if (!CollectionUtils.isEmpty(itemList)) {
            stableDetailList = itemList.get(0).getStableDetailList();
            //固有风险配置
            RiskEvaluationControl stableConfig = riskEvaluationControlDao.findByName(BaseConfigCodes.WWYT_RISK_NAME);
            if (stableConfig.getSwitchState() != null && stableConfig.getSwitchState().intValue() == 0) {
                stableDetailList = null;
            }
        }

        RiskPoint riskPoint = riskPointDao.findById(bean.getPointId()).orElseThrow(() -> new IllegalArgumentException("风险点不存在"));
        Integer shared = riskPoint.getShared();

        //控制评估
        RiskPointEvaluationBusiness controlPointBusiness = null;
        //固有评估
        RiskPointEvaluationBusiness stablePointBusiness = null;
        Long stableEvaluationId = null;
        //风险点评估值
        String pointControlEvaluationValue = null;
        //固有评估item集合
        List<Long> stableItemIds = new ArrayList<>();

        //删除数据
        if (!CollectionUtils.isEmpty(bean.getDeleteItemIds())) {
            riskPointEvaluationItemDao.deleteAllByIds(bean.getDeleteItemIds());
            riskPointEvaluationDetailDao.deleteByItemIds(bean.getDeleteItemIds());
            for (Long id : bean.getDeleteItemIds()) {
                Optional<RiskPointEvaluationItem> oet = riskPointEvaluationItemDao.findById(id);
                if (oet.isPresent()) {
                    riskPointEvaluationItemDao.deleteById(id);
                    // recalculateDistrictRealTimeRiskLevel(oet.get(), ControlRiskLevelType.EFFICIENT.getValue());
                }
            }
        }
        if (!CollectionUtils.isEmpty(bean.getDeleteDetailIds())) {
            riskPointEvaluationDetailDao.deleteByIds(bean.getDeleteDetailIds());
        }

        if (!CollectionUtils.isEmpty(itemList)) {
            //固有评估
            if (!CollectionUtils.isEmpty(stableDetailList)) {
                PointlEvaluationItemForAssessmentReturnBean stableReturnBean = covertPointEvaluationForAssessment(shared, bean, pointControlEvaluationValue, null, AnalyzeTypeEnum.FIXED.getValue(), stableItemIds);
                if (stableReturnBean != null) {
                    stablePointBusiness = stableReturnBean.getBusiness();
                    stableItemIds = stableReturnBean.getControlItemIds();
                }
            }
            if (stablePointBusiness != null) {
                stableEvaluationId = stablePointBusiness.getId();
            }
            //控制评估
            PointlEvaluationItemForAssessmentReturnBean controlReturnBean = covertPointEvaluationForAssessment(shared, bean, pointControlEvaluationValue, stableEvaluationId, AnalyzeTypeEnum.CONTROLLABLE.getValue(), stableItemIds);
            if (controlReturnBean != null) {
                controlPointBusiness = controlReturnBean.getBusiness();
            }
        }

        //更新风险点 风险区域 风险区域评估等级
        Integer oldLevel = null;
        RiskPoint point = riskPointDao.findById(controlPointBusiness.getPointId()).orElseThrow(() -> new IllegalArgumentException("风险点不存在"));
        if (point.getRiskDistrict() != null) {
            oldLevel = point.getRiskDistrict().getRiskLevel();
        }
        if (CollectionUtils.isEmpty(stableDetailList)) {
            point.setStableRiskLevel(null);
        }

        //修改风险点内容
        editPointDataForAssessment(bean, point, pointControlEvaluationValue, controlPointBusiness.getAnalyzeWayId(), controlPointBusiness, stablePointBusiness, oldLevel);
        return controlPointBusiness;
    }

    /**
     * 保存风险点评估
     *
     * @param shared
     * @param bean
     * @param pointControlEvaluationValue
     * @param saveFlag
     * @return
     * @throws BusinessRestrictionsException
     */
    private PointlEvaluationItemForAssessmentReturnBean covertPointEvaluationForAssessment(Integer shared, RiskPointEvaluationBusinessBean bean,
                                                                                           String pointControlEvaluationValue, Long stableEvaluationId, Integer saveFlag, List<Long> stableItemIds) throws BusinessRestrictionsException {
        PointlEvaluationItemForAssessmentReturnBean returnBean = new PointlEvaluationItemForAssessmentReturnBean();
        RiskPointEvaluationBusiness business = new RiskPointEvaluationBusiness();
        if (saveFlag.equals(AnalyzeTypeEnum.CONTROLLABLE.getValue())) {
            if (bean.getPointBusinessId() != null) {
                business = pointEvaluationBusinessDao.findById(bean.getPointBusinessId()).orElseThrow(() -> new IllegalArgumentException("风险评估不存在"));
            }
            BeanUtils.copyProperties(bean, business);
            business.setRiskLevel(bean.getRiskLevel());
            business.setStableEvaluationId(stableEvaluationId);
            business.setPointAnalyzeType(AnalyzeTypeEnum.CONTROLLABLE.getValue());
        } else if (saveFlag.equals(AnalyzeTypeEnum.FIXED.getValue())) {
            if (bean.getStablePointBusinessId() != null) {
                business = pointEvaluationBusinessDao.findById(bean.getStablePointBusinessId()).orElseThrow(() -> new IllegalArgumentException("风险评估不存在"));
            }
            BeanUtils.copyProperties(bean, business);
            business.setRiskLevel(bean.getStableRiskLevel());
            business.setPointAnalyzeType(AnalyzeTypeEnum.FIXED.getValue());
        }
        //风险点类别:null风险点;1风险点库
        business.setShared(shared);
        if (!CollectionUtils.isEmpty(bean.getEvaluationUserIds())) {
            business.setEvaluationUserIds(JSONArray.toJSONString(bean.getEvaluationUserIds()));
        }
        business = pointEvaluationBusinessDao.save(business);

        //保存item
        if (!CollectionUtils.isEmpty(bean.getItemList())) {
            int orderNumber = 1;
            for (int i = 0; i < bean.getItemList().size(); i++) {
                RiskPointEvaluationItemAddBean itemAddBean = bean.getItemList().get(i);
                itemAddBean.setOrderNumber(orderNumber++);
                RiskPointEvaluationItem item = savePointEvaluationItemForAssessment(shared, business, bean, itemAddBean, pointControlEvaluationValue, saveFlag);
                //保存固有风险item id
                if (saveFlag.equals(AnalyzeTypeEnum.FIXED.getValue())) {
                    stableItemIds.add(item.getId());
                } else if (saveFlag.equals(AnalyzeTypeEnum.CONTROLLABLE.getValue())) {
                    if (!CollectionUtils.isEmpty(stableItemIds)) {
                        item.setStableItemId(stableItemIds.get(i));
                    }
                    riskPointEvaluationItemDao.save(item);
                }
            }
        }
        returnBean.setBusiness(business);
        returnBean.setControlItemIds(stableItemIds);
        return returnBean;
    }

    /**
     * 保存风险点控制评估item
     *
     * @param
     */
    private RiskPointEvaluationItem savePointEvaluationItemForAssessment(Integer shared, RiskPointEvaluationBusiness business, RiskPointEvaluationBusinessBean bean,
                                                                         RiskPointEvaluationItemAddBean itemAddBean, String pointControlEvaluationValue, Integer saveFlag) throws BusinessRestrictionsException {
        Integer riskLevel = null;
        Long itemId = null;
        if (saveFlag.equals(AnalyzeTypeEnum.CONTROLLABLE.getValue())) {
            riskLevel = itemAddBean.getRiskLevel();
            itemId = itemAddBean.getId();
        } else if (saveFlag.equals(AnalyzeTypeEnum.FIXED.getValue())) {
            riskLevel = itemAddBean.getStableRiskLevel();
            itemId = itemAddBean.getStableItemId();
        }
        //item
        RiskPointEvaluationItem pointItem = savePointBaseEvaluationItemForAssessment(itemId, saveFlag, riskLevel, itemAddBean.getOrderNumber(), bean, business.getId(), shared);
        //保存控制评估detail集合
        if (saveFlag.equals(AnalyzeTypeEnum.CONTROLLABLE.getValue())) {
            savePointControlEvaluationDetailListForAssessment(shared, business, bean, itemAddBean.getDetailList(), pointItem, pointControlEvaluationValue);
        } else if (saveFlag.equals(AnalyzeTypeEnum.FIXED.getValue())) {
            List<RiskPointStableDetailBean> stableDetailList = itemAddBean.getStableDetailList();
            if (!CollectionUtils.isEmpty(stableDetailList)) {
                for (RiskPointStableDetailBean detailBean : stableDetailList) {
                    //Integer shared, RiskPointEvaluationBusinessBean bean, RiskPointEvaluationDetailAddBean detailAddBean, Long pointBusinessId, Long itemId
                    RiskPointEvaluationDetail detail = covertStableEvaluationBaseDetail(shared, bean, detailBean, business.getId(), pointItem.getId(), AnalyzeTypeEnum.FIXED.getValue());
                    riskPointEvaluationDetailDao.save(detail);
                }
            }
        }
        return pointItem;
    }


    /**
     * 保存风险点item基础数据
     *
     * @param id
     * @param riskLevel
     * @param orderNumber
     * @param bean
     * @param pointBusinessId
     * @param shared
     * @param saveFlag
     * @return
     */
    private RiskPointEvaluationItem savePointBaseEvaluationItemForAssessment(Long id, Integer saveFlag, Integer riskLevel, Integer orderNumber, RiskPointEvaluationBusinessBean bean, Long pointBusinessId, Integer shared) {
        RiskPointEvaluationItem item = new RiskPointEvaluationItem();
        if (id != null) {
            item = riskPointEvaluationItemDao.findById(id).orElseThrow(() -> new IllegalArgumentException("评估序号不存在"));
        }
        //评估等级
        item.setRiskLevel(riskLevel);
        //序号
        item.setOrderNumber(orderNumber);
        //风险点id
        item.setRiskPointId(bean.getPointId());
        //0风险点固有风险评价,1风险点控制风险评价
        item.setPointAnalyzeType(saveFlag);
        //分析方法id
        item.setAnalyzeWayId(bean.getAnalyzeWayId());
        //评估id
        item.setPointEvaluationId(pointBusinessId);
        //风险点类别:null风险点;1风险点库"
        item.setShared(shared);
        if (item.getControlFailureCount() == null) {
            item.setControlFailureCount(0);
        }
        //具体详情
        RiskPointEvaluationItem pointItem = riskPointEvaluationItemDao.save(item);
        return pointItem;
    }

    /**
     * 保存控制评估detail集合
     *
     * @param shared
     * @param business
     * @param bean
     * @param detailList
     * @param pointItem
     * @param pointControlEvaluationValue
     * @throws BusinessRestrictionsException
     */
    private void savePointControlEvaluationDetailListForAssessment(Integer shared, RiskPointEvaluationBusiness business, RiskPointEvaluationBusinessBean bean, List<RiskPointEvaluationDetailAddBean> detailList,
                                                                   RiskPointEvaluationItem pointItem, String pointControlEvaluationValue) throws BusinessRestrictionsException {
        if (!CollectionUtils.isEmpty(detailList)) {
            List<String> methodKey = detailList.stream().filter(each -> each.getMethodAnalyzeType().equals(MethodAnalyzeType.CONTROL_MEASURES.getCode()))
                    .map(r -> r.getMethodId() + "_" + r.getContent()).collect(Collectors.toList());
            HashSet<String> methodKeySet = new HashSet<>(methodKey);
            if (methodKey.size() > methodKeySet.size()) {
                throw new BusinessRestrictionsException(Status.HAS_SAME_CONTROL_MEASURES_AND_CONTENT.getMsg());
            }
            for (RiskPointEvaluationDetailAddBean detailAddBean : detailList) {
                //管控措施 详情
                RiskPointEvaluationDetail detail = covertEvaluationDetail(shared, detailAddBean, bean, business.getId(), pointItem.getId(), pointControlEvaluationValue);
                RiskPointEvaluationDetail saveResult = riskPointEvaluationDetailDao.save(detail);
                // 排查内容
                if (MethodAnalyzeType.CONTROL_MEASURES.getCode().equals(saveResult.getMethodAnalyzeType())) {
                    ArrayList<RiskHiddenDangerContent> riskHiddenDangerContents = new ArrayList<>();
                    List<Long> contentIds = new ArrayList<>();
                    detailAddBean.getHiddenDangerContent().forEach(each -> {
                        RiskHiddenDangerContent hiddenDangerContent = new RiskHiddenDangerContent();
                        BeanUtils.copyProperties(each, hiddenDangerContent);
                        hiddenDangerContent.setDetailId(saveResult.getId());
                        riskHiddenDangerContents.add(hiddenDangerContent);
                        if (DeleteFlag.DELETED.getCode().equals(each.getDeleteFlag())) {
                            contentIds.add(each.getId());
                        }
                    });
                    if (!CollectionUtils.isEmpty(contentIds)) {
                        bpInvestigatePlanRepository.updateInitiateStatusByIds(contentIds);
                    }
                    if (!CollectionUtils.isEmpty(riskHiddenDangerContents)) {
                        riskHiddenDangerContentService.saveOrUpdateBatch(riskHiddenDangerContents);
                    }
                }
            }
        }
    }


    /**
     * 更新风险点内容
     *
     * @param bean
     * @param point
     * @param pointEvaluationValue
     * @param analyzeWayId
     * @param controlPointBusiness
     * @param stablePointBusiness
     * @return
     */
    private void editPointDataForAssessment(RiskPointEvaluationBusinessBean bean, RiskPoint point, String pointEvaluationValue, Long analyzeWayId, RiskPointEvaluationBusiness controlPointBusiness,

                                            RiskPointEvaluationBusiness stablePointBusiness, Integer oldLevel) {
        //是否是新增 true:新增 false 修改
        boolean controlSaveFlag = bean.getPointBusinessId() == null ? true : false;
        boolean stableSaveFlag = bean.getStablePointBusinessId() == null ? true : false;
        RiskPointEvaluationBusiness controlEvaluation = getLastRiskPointEvaluationBusiness(point.getId(), 1);
        //获取最后一次固有评估
        RiskPointEvaluationBusiness stableEvaluation = null;
        if (controlEvaluation.getStableEvaluationId() != null) {
            Optional<RiskPointEvaluationBusiness> orb = riskPointEvaluationBusinessDao.findById(controlEvaluation.getStableEvaluationId());
            if (orb.isPresent()) {
                stableEvaluation = orb.get();
            }
        }

        if (stablePointBusiness != null && stableEvaluation != null) {
            // 1.新增操作,新评估日期不小于当前日期 2.修改操作,修改最近的固有评估
            //只有满足以上俩的一个才能更新风险点的固有内容
            if ((stableSaveFlag && !stablePointBusiness.getEvaluationDate().before(stableEvaluation.getEvaluationDate()) || (!stableSaveFlag && stableEvaluation.getId().equals(stablePointBusiness.getId())))) {
                //如果传入的固有评估时间在上一次的之后,则修改固有评估的值
                point.setStableRiskLevel(stablePointBusiness.getRiskLevel());
            }
        }

        if (controlPointBusiness != null && controlEvaluation != null) {
            //1.新增操作,新评估日期不小于当前日期 2.修改操作,修改最近的控制评估
            //只有满足以上俩点的一个才能更新风险点的控制内容
            if ((controlSaveFlag && !controlPointBusiness.getEvaluationDate().before(controlEvaluation.getEvaluationDate())) || (!controlSaveFlag && controlEvaluation.getId().equals(controlPointBusiness.getId()))) {
                point.setControlRiskLevel(controlPointBusiness.getRiskLevel());
                //风险点评估值
                point.setPointEvaluationValue(pointEvaluationValue);
                //评估时 实时等级和评估等级一致
                point.setRiskLevel(controlPointBusiness.getRiskLevel());
                //重新计算实时等级
                point.setRealTimeRiskLevel(recalculatePointRealRiskLevel(point, controlPointBusiness.getId(), null, ControlRiskLevelType.EFFICIENT.getValue()));
                //设置风险点执行人
                point = saveRiskForAssessment(bean.getEvaluationUserIds(), point, analyzeWayId);
                //新增:删除该风险点下的排查计划
                if (controlSaveFlag) {
                    List<Long> riskHiddenDangerContentIds = riskHiddenDangerContentService.findIdsByRiskPoints(Lists.newArrayList(point.getId()));
                    if (riskHiddenDangerContentIds != null && !riskHiddenDangerContentIds.isEmpty()) {
                        bpInvestigatePlanService.updateInitiateStatusByIds(riskHiddenDangerContentIds);
                    }
                }
                point.setLastEvaluationTime(controlPointBusiness.getEvaluationDate());
                riskPointDao.save(point);
                //更改风险点评估计划
                riskEvaluationPlanService.riskPointReCal(point, bean.getEvaluationDate(), 1);
                if (point.getRiskDistrict() != null) {
                    point.getRiskDistrict().setEvaluationState(1);
                    editDistrictLevel(point.getRiskDistrict(), oldLevel, "区域风险评估");
                }
            }
        }

    }


    private RiskPoint saveRiskForAssessment(List<Long> evaluationUserIds, RiskPoint point, Long analyzeWayId) {
        //保存评估人
        String evaluatorIdJson = point.getEvaluatorIdJson();
        Map<String, List<Long>> map = new HashMap<>();
        if (StringUtils.isNotBlank(evaluatorIdJson)) {
            map = (Map) JSONObject.parse(evaluatorIdJson);
        }
        map.put(analyzeWayId.toString(), evaluationUserIds);
        point.setEvaluatorIdJson(JSONArray.toJSONString(map));
        return point;
    }


    private RiskPointEvaluationItem covertPointEvaluationItem(RiskPointEvaluationItemAddBean itemAddBean, RiskPointEvaluationBusinessBean bean, Long pointBusinessId, Integer shared, Integer analyzeType) {
        RiskPointEvaluationItem item = new RiskPointEvaluationItem();
        if (analyzeType.equals(AnalyzeTypeEnum.CONTROLLABLE.getValue()))
            if (itemAddBean.getId() != null) {
                item = riskPointEvaluationItemDao.findById(itemAddBean.getId()).orElseThrow(() -> new IllegalArgumentException("评估序号不存在"));
            }
        //评估等级
        if (analyzeType.equals(AnalyzeTypeEnum.CONTROLLABLE.getValue())) {
            item.setRiskLevel(itemAddBean.getRiskLevel());
        } else if (analyzeType.equals(AnalyzeTypeEnum.FIXED.getValue())) {
            item.setRiskLevel(itemAddBean.getStableRiskLevel());
        }
        //序号
        item.setOrderNumber(itemAddBean.getOrderNumber());
        //风险点id
        item.setRiskPointId(bean.getPointId());
        //0风险点固有风险评价,1风险点控制风险评价
        item.setPointAnalyzeType(analyzeType);
        //分析方法id
        item.setAnalyzeWayId(bean.getAnalyzeWayId());
        //评估id
        item.setPointEvaluationId(pointBusinessId);
        //风险点类别:null风险点;1风险点库"
        item.setShared(shared);
        if (item.getControlFailureCount() == null) {
            item.setControlFailureCount(0);
        }
        //具体详情
        return item;
    }

    private RiskPointEvaluationDetail covertEvaluationDetail(Integer shared, RiskPointEvaluationDetailAddBean detailAddBean, RiskPointEvaluationBusinessBean bean, Long pointBusinessId, Long itemId, String pointControlEvaluationValue) {
        RiskPointEvaluationDetail detail = covertEvaluationBaseDetail(shared, bean, detailAddBean, pointBusinessId, itemId, AnalyzeTypeEnum.CONTROLLABLE.getValue());
        //获取风险点评估值
        if (bean.getPointAnalyzeType() != null && bean.getPointAnalyzeType().intValue() == 1
                && detailAddBean.getMethodAnalyzeType() != null && detailAddBean.getMethodAnalyzeType().intValue() == 1
                && detailAddBean.getContentType() != null && detailAddBean.getContentType().intValue() == 1) {
            if (pointControlEvaluationValue == null) {
                pointControlEvaluationValue = detailAddBean.getContent();
            } else {
                if (Double.valueOf(pointControlEvaluationValue) < Double.valueOf(detailAddBean.getContent())) {
                    pointControlEvaluationValue = detailAddBean.getContent();
                }
            }
        }
        //管控措施添加管控状态管控状态
        if (shared == null || shared == 0) {
            if (detailAddBean.getMethodAnalyzeType() != null && detailAddBean.getMethodAnalyzeType() == 2) {
                //region 将管控层级、责任人、责任单位 List[1, 2, 3]的数据转换为字符串1,2,3的格式
                List<Long> controlLevelIds = detailAddBean.getControlLevelIds();
                if (!CollectionUtils.isEmpty(controlLevelIds)) {
                    String levelIds = controlLevelIds.stream().map(String::valueOf)
                            .collect(Collectors.joining(Constant.SPLIT_COMMA));
                    detail.setControlLevelIds(levelIds);
                }
                List<Long> responseDepartIds = detailAddBean.getResponseDepartIds();
                if (!CollectionUtils.isEmpty(responseDepartIds)) {
                    String departIds = responseDepartIds.stream().map(String::valueOf)
                            .collect(Collectors.joining(Constant.SPLIT_COMMA));
                    detail.setResponseDepartIds(departIds);
                }
                List<Long> responseUserIds = detailAddBean.getResponseUserIds();
                if (!CollectionUtils.isEmpty(responseUserIds)) {
                    String userIds = responseDepartIds.stream().map(String::valueOf)
                            .collect(Collectors.joining(Constant.SPLIT_COMMA));
                    detail.setResponseUserIds(userIds);
                }
                //endregion
                if (detailAddBean.getControlState() != null) {
                    detail.setControlState(detailAddBean.getControlState());
                } else {
                    detail.setControlState(1);
                }
            }
        }
        return detail;
    }

    private RiskPointEvaluationDetail covertStableEvaluationDetail(Integer shared, RiskPointStableDetailBean detailAddBean, RiskPointEvaluationBusinessBean bean, Long pointBusinessId, Long itemId, String pointControlEvaluationValue) {
        RiskPointEvaluationDetail detail = covertStableEvaluationBaseDetail(shared, bean, detailAddBean, pointBusinessId, itemId, AnalyzeTypeEnum.FIXED.getValue());
        //获取风险点评估值
        if (bean.getPointAnalyzeType() != null && bean.getPointAnalyzeType().intValue() == 1
                && detailAddBean.getMethodAnalyzeType() != null && detailAddBean.getMethodAnalyzeType().intValue() == 1
                && detailAddBean.getContentType() != null && detailAddBean.getContentType().intValue() == 1) {
            if (pointControlEvaluationValue == null) {
                pointControlEvaluationValue = detailAddBean.getContent();
            } else {
                if (Double.valueOf(pointControlEvaluationValue) < Double.valueOf(detailAddBean.getContent())) {
                    pointControlEvaluationValue = detailAddBean.getContent();
                }
            }
        }
        return detail;
    }

    /**
     * 保存detail基础数据
     *
     * @param shared
     * @param bean
     * @param detailAddBean
     * @param pointBusinessId
     * @param itemId
     * @return
     */
    private RiskPointEvaluationDetail covertEvaluationBaseDetail(Integer shared, RiskPointEvaluationBusinessBean bean, RiskPointEvaluationDetailAddBean detailAddBean, Long pointBusinessId, Long itemId, Integer pointAnalyzeType) {
        RiskPointEvaluationDetail detail = new RiskPointEvaluationDetail();
        if (detailAddBean.getId() != null) {
            detail = riskPointEvaluationDetailDao.findById(detailAddBean.getId()).orElseThrow(() -> new IllegalArgumentException("评估内容不存在"));
        }
        //风险点id
        detail.setRiskPointId(bean.getPointId());
        //0风险点固有风险评价,1风险点控制风险评价
        detail.setPointAnalyzeType(pointAnalyzeType);
        //分析方法id
        detail.setAnalyzeWayId(bean.getAnalyzeWayId());
        //评估id
        detail.setPointEvaluationId(pointBusinessId);
        //风险辨识评估id
        detail.setItemId(itemId);
        //类型:0分析方法选项,1评估方法选项,2数据字典(管控措施id)
        detail.setMethodAnalyzeType(detailAddBean.getMethodAnalyzeType());
        //选项id
        detail.setMethodId(detailAddBean.getMethodId());
        //选项类型 0文本,1下拉选
        detail.setContentType(detailAddBean.getContentType());
        //所选指标选项id
        detail.setTargetItemId(detailAddBean.getTargetItemId());
        //管控措施内容
        detail.setContent(detailAddBean.getContent());
        //风险点类别:null风险点;1风险点库
        detail.setShared(shared);
        return detail;
    }

    private RiskPointEvaluationDetail covertStableEvaluationBaseDetail(Integer shared, RiskPointEvaluationBusinessBean bean, RiskPointStableDetailBean detailAddBean, Long pointBusinessId, Long itemId, Integer pointAnalyzeType) {
        RiskPointEvaluationDetail detail = new RiskPointEvaluationDetail();
        if (detailAddBean.getId() != null) {
            detail = riskPointEvaluationDetailDao.findById(detailAddBean.getId()).orElseThrow(() -> new IllegalArgumentException("评估内容不存在"));
        }
        //风险点id
        detail.setRiskPointId(bean.getPointId());
        //0风险点固有风险评价,1风险点控制风险评价
        detail.setPointAnalyzeType(pointAnalyzeType);
        //分析方法id
        detail.setAnalyzeWayId(bean.getAnalyzeWayId());
        //评估id
        detail.setPointEvaluationId(pointBusinessId);
        //风险辨识评估id
        detail.setItemId(itemId);
        //类型:0分析方法选项,1评估方法选项,2数据字典(管控措施id)
        detail.setMethodAnalyzeType(detailAddBean.getMethodAnalyzeType());
        //选项id
        detail.setMethodId(detailAddBean.getMethodId());
        //选项类型 0文本,1下拉选
        detail.setContentType(detailAddBean.getContentType());
        //所选指标选项id
        detail.setTargetItemId(detailAddBean.getTargetItemId());
        //管控措施内容
        detail.setContent(detailAddBean.getContent());
        //风险点类别:null风险点;1风险点库
        detail.setShared(shared);
        return detail;
    }

    private RiskPoint editPointData(RiskPointEvaluationBusinessBean bean, RiskPoint point, String pointEvaluationValue, Long analyzeWayId) {
        //固有等级
        Integer stableLevel = null;
        //控制等级
        Integer controlLevel = null;
        //风险点的上一次评估时间
        Date lastEvaluationTime = point.getLastEvaluationTime();
        //获取最后一次控制评估
        RiskPointEvaluationBusiness controlEvaluation = getLastRiskPointEvaluationBusiness(point.getId(), 1);
        //获取最后一次固有评估
        RiskPointEvaluationBusiness stableEvaluation = getLastRiskPointEvaluationBusiness(point.getId(), 0);
        //判断是固有还是控制，0是固有，1是控制
        if (bean.getPointAnalyzeType() != null && 0 == bean.getPointAnalyzeType()) {
            //传入的固有评估的等级
            stableLevel = bean.getRiskLevel();
            //上一次的固有评估时间
            Date lastStableEvaluationTime = stableEvaluation.getEvaluationDate();
            //如果有控制评估则拿到其最后一次的控制等级
            if (controlEvaluation != null) {
                controlLevel = controlEvaluation.getRiskLevel();
            }
            //如果传入的固有评估时间在上一次的之后,则修改固有评估的值
            if (!bean.getEvaluationDate().before(lastStableEvaluationTime)) {
                point.setStableRiskLevel(bean.getRiskLevel());
//                //风险点评估值
//                point.setPointEvaluationValue(pointEvaluationValue);
                //设置风险点的危险等级和执行人
                RiskPoint riskPoint = setRiskLevelAndEvaluator(bean, point, stableLevel, controlLevel, analyzeWayId);
                //如果传入的固有评估时间在风险点的上一次的评估时间之后则去更改
//                if (null == lastEvaluationTime || bean.getEvaluationDate().after(lastEvaluationTime)) {
//                    point.setLastEvaluationTime(bean.getEvaluationDate());
//                    return riskPointDao.save(riskPoint);
//                }
                return riskPointDao.save(riskPoint);
            }
            //如果是控制
        } else if (bean.getPointAnalyzeType() != null && 1 == bean.getPointAnalyzeType()) {
            //传入的控制评估的等级
            controlLevel = bean.getRiskLevel();
            //上一次的控制评估时间
            Date lastControlEvaluationTime = controlEvaluation.getEvaluationDate();
            //如果有固有评估则拿到其最后一次的固有等级
            if (stableEvaluation != null) {
                stableLevel = stableEvaluation.getRiskLevel();
            }
            //如果传入的控制评估时间在上一次的之后,则修改控制评估的值
            if (!bean.getEvaluationDate().before(lastControlEvaluationTime)) {
                point.setControlRiskLevel(bean.getRiskLevel());
                //风险点评估值
                point.setPointEvaluationValue(pointEvaluationValue);
                //设置风险点的危险等级和执行人
                RiskPoint riskPoint = setRiskLevelAndEvaluator(bean, point, stableLevel, controlLevel, analyzeWayId);
                //如果传入的固有评估时间在风险点的上一次的评估时间之后则去更改
                if (null == lastEvaluationTime || bean.getEvaluationDate().after(lastEvaluationTime)) {
                    point.setLastEvaluationTime(bean.getEvaluationDate());
                    return riskPointDao.save(riskPoint);
                }
                return riskPointDao.save(riskPoint);
            }
        }
        return point;
    }

    private RiskPoint setRiskLevelAndEvaluator(RiskPointEvaluationBusinessBean bean, RiskPoint point, Integer stableLevel, Integer controlLevel, Long analyzeWayId) {
        Integer riskLevel;
        if (stableLevel == null && controlLevel != null) {
            riskLevel = controlLevel;
        } else if (stableLevel != null && controlLevel == null) {
            riskLevel = stableLevel;
        } else if (stableLevel != null && controlLevel != null) {
            if (stableLevel > controlLevel) {
                riskLevel = stableLevel;
            } else {
                riskLevel = controlLevel;
            }
        } else {
            riskLevel = null;
        }
        point.setRiskLevel(riskLevel);
        //保存评估人
        String evaluatorIdJson = point.getEvaluatorIdJson();
        Map<String, List<Long>> map = new HashMap<>();
        if (StringUtils.isNotBlank(evaluatorIdJson)) {
            map = (Map) JSONObject.parse(evaluatorIdJson);
        }
        map.put(analyzeWayId.toString(), bean.getEvaluationUserIds());
        point.setEvaluatorIdJson(JSONArray.toJSONString(map));
        return point;
    }


    /**
     * 查看风险点风险评估（作业分析库页面）
     *
     * @param riskPointId
     * @param pointAnalyzeType
     * @param analyzeWayId
     * @param riskPointEvaluationId
     * @return
     */
    @Override
    public RiskPointEvaluationBusinessShowBean getPointEvaluation(Long riskPointId, Integer pointAnalyzeType, Long analyzeWayId, Long riskPointEvaluationId) {
        RiskPointEvaluationBusiness pointBusiness = null;
        if (riskPointEvaluationId != null) {
            pointBusiness = pointEvaluationBusinessDao.findById(riskPointEvaluationId).orElse(null);
        } else {
            pointBusiness = pointEvaluationBusinessDao.getPointEvaluation(riskPointId, pointAnalyzeType, analyzeWayId);
            RiskEvaluationControl control = riskEvaluationControlDao.findByName(BaseConfigCodes.WWYT_RISK_NAME);
            if (pointBusiness == null || (pointAnalyzeType != null && pointAnalyzeType.intValue() == 0 && control.getSwitchState() != null && control.getSwitchState().intValue() == 0)) {
                return null;
            }
        }
        RiskPointEvaluationBusinessShowBean businessShowBean = new RiskPointEvaluationBusinessShowBean();
        BeanUtils.copyProperties(pointBusiness, businessShowBean);
        //风险点类型
        businessShowBean.setPointType(getPointTypeName(pointBusiness.getPointId()));
        //风险等级名称
        businessShowBean.setRiskLevelName(RiskLevels.findRiskLevelName(pointBusiness.getRiskLevel()));
        //评估人员名称
        if (StringUtils.isNotBlank(pointBusiness.getEvaluationUserIds())) {
            List<Long> evaluationUserIds = StringUtil.covertJsonToLongList(pointBusiness.getEvaluationUserIds());
            if (!CollectionUtils.isEmpty(evaluationUserIds)) {
                businessShowBean.setEvaluationUserIds(evaluationUserIds);
                List<SimpleListBean> evaluationUserBeanList = getEvaluationUserBean(evaluationUserIds);
                if (!CollectionUtils.isEmpty(evaluationUserBeanList)) {
                    businessShowBean.setEvaluationUserBeanList(evaluationUserBeanList);
                }
            }
        }
        List<RiskPointEvaluationItemShowBean> itemList = new ArrayList<>();
        //获取风险辨识评估
        List<RiskPointEvaluationItem> iteList = riskPointEvaluationItemDao.findByPointEvaluationId(pointBusiness.getId());
        if (!CollectionUtils.isEmpty(iteList)) {
            for (RiskPointEvaluationItem item : iteList) {
                RiskPointEvaluationItemShowBean bean = new RiskPointEvaluationItemShowBean();
                BeanUtils.copyProperties(item, bean);
                if (item.getRiskLevel() != null) {
                    bean.setRiskLevelName(RiskLevels.findRiskLevelName(item.getRiskLevel()));
                }
                //获取风险辨识评估详情
                List<RiskPointEvaluationDetail> dList = riskPointEvaluationDetailDao.findByItemId(item.getId());
                List<RiskPointEvaluationDetailShowBean> detailList = new ArrayList<>();
                if (!CollectionUtils.isEmpty(dList)) {
                    for (RiskPointEvaluationDetail detail : dList) {
                        RiskPointEvaluationDetailShowBean detailBean = new RiskPointEvaluationDetailShowBean();
                        BeanUtils.copyProperties(detail, detailBean);
                        //选项名称
                        if (detail.getMethodId() != null) {
                            if (detail.getMethodAnalyzeType() != null && detail.getMethodAnalyzeType().intValue() != 2) {
                                Optional<RiskEvaluationAnalyzeMethod> sem = analyzeMethodDao.findById(detail.getMethodId());
                                if (sem.isPresent()) {
                                    detailBean.setMethodName(sem.get().getName());
                                } else {
                                    //当前配置项查不到 则返回null
                                    detailBean.setMethodId(null);
                                    detailBean.setMethodName(null);
                                }
                            } else if (detail.getMethodAnalyzeType() != null && detail.getMethodAnalyzeType().intValue() == 2) {
                                //管控措施
                                Optional<BaseTypeGroupItem> btg = baseTypeGroupItemDao.findById(detail.getMethodId());
                                if (btg.isPresent()) {
                                    detailBean.setMethodName(btg.get().getName());
                                } else {
                                    detailBean.setMethodId(null);
                                    detailBean.setMethodName(null);
                                }
                            }
                        }
                        //所选指标选项名称
                        if (detail.getTargetItemId() != null) {
                            Optional<RiskEvaluationTargetItem> reti = targetItemDao.findById(detail.getTargetItemId());
                            if (reti.isPresent()) {
                                detailBean.setTargetItemName(reti.get().getName());
                                detailBean.setScore(reti.get().getScore());
                            } else {
                                detailBean.setTargetItemName(null);
                                detailBean.setTargetItemId(null);
                            }
                        }
                        detailList.add(detailBean);
                    }
                }
                bean.setDetailList(detailList);
                itemList.add(bean);
            }
        }
        businessShowBean.setItemList(itemList);
        return businessShowBean;
    }


    /**
     * 查看风险点风险评估(风险评估页面)
     *
     * @param riskPointId
     * @param analyzeWayId
     * @param riskEvaluationId
     * @return
     */
    @Override
    public RiskPointEvaluationBusinessShowBean getPointEvaluationForAssessment(Long riskPointId, Long analyzeWayId, Long riskEvaluationId) {
        RiskPointEvaluationBusiness controlEvaluation = null;
        RiskPointEvaluationBusiness stableEvaluation = null;
        Long stablePointEvaluationId = null;
        //控制评估
        if (riskEvaluationId != null) {
            controlEvaluation = pointEvaluationBusinessDao.findById(riskEvaluationId).orElseThrow(() -> new IllegalArgumentException("该控制评估不存在"));
        } else {
            controlEvaluation = pointEvaluationBusinessDao.getPointEvaluation(riskPointId, AnalyzeTypeEnum.CONTROLLABLE.getValue(), analyzeWayId);
            if (controlEvaluation == null) {
                return null;
            }
        }
        RiskEvaluationControl control = riskEvaluationControlDao.findByName(BaseConfigCodes.WWYT_RISK_NAME);
        //固有评估
        if (controlEvaluation.getStableEvaluationId() != null) {
            stableEvaluation = pointEvaluationBusinessDao.findById(controlEvaluation.getStableEvaluationId()).orElseThrow(() -> new IllegalArgumentException("固有评估不存在"));
            if (control != null && control.getSwitchState().intValue() == 0) {
                stableEvaluation = null;
            }

        }
        RiskPointEvaluationBusinessShowBean businessShowBean = new RiskPointEvaluationBusinessShowBean();
        BeanUtils.copyProperties(controlEvaluation, businessShowBean);
        //风险点类型
        businessShowBean.setPointType(getPointTypeName(controlEvaluation.getPointId()));
        businessShowBean.setDeafultDate(DateTimeUtil.localDateTime2Date(controlEvaluation.getUpdateTime()));

        //评估人员名称
        if (StringUtils.isNotBlank(controlEvaluation.getEvaluationUserIds())) {
            List<Long> evaluationUserIds = StringUtil.covertJsonToLongList(controlEvaluation.getEvaluationUserIds());
            if (!CollectionUtils.isEmpty(evaluationUserIds)) {
                businessShowBean.setEvaluationUserIds(evaluationUserIds);
                List<SimpleListBean> evaluationUserBeanList = getEvaluationUserBean(evaluationUserIds);
                if (!CollectionUtils.isEmpty(evaluationUserBeanList)) {
                    businessShowBean.setEvaluationUserBeanList(evaluationUserBeanList);
                }
            }
        }
        //风险等级名称
        businessShowBean.setRiskLevelName(RiskLevels.findRiskLevelName(controlEvaluation.getRiskLevel()));
        if (stableEvaluation != null) {
            businessShowBean.setStableRiskLevel(stableEvaluation.getRiskLevel());
            businessShowBean.setStableRiskLevelName(RiskLevels.findRiskLevelName(stableEvaluation.getRiskLevel()));
            stablePointEvaluationId = stableEvaluation.getId();
            if (control != null && control.getSwitchState().intValue() == 0) {
                stablePointEvaluationId = null;
            }
            businessShowBean.setStablePointBusinessId(stablePointEvaluationId);
        }
        businessShowBean.setItemList(getPointControlEvaluationItems(controlEvaluation.getId(), stablePointEvaluationId, control));
        return businessShowBean;
    }

    private List<RiskPointEvaluationItemShowBean> getPointControlEvaluationItems(Long pointEvaluationId, Long stablePointEvaluationId, RiskEvaluationControl control) {
        List<RiskPointEvaluationItemShowBean> itemList = new ArrayList<>();
        List<RiskPointEvaluationItem> stableItemList = null;
        //获取风险辨识评估
        List<RiskPointEvaluationItem> iteList = riskPointEvaluationItemDao.findByPointEvaluationId(pointEvaluationId);
        if (stablePointEvaluationId != null) {
            stableItemList = riskPointEvaluationItemDao.findByPointEvaluationId(stablePointEvaluationId);
        }
        if (CollectionUtils.isEmpty(iteList) && !CollectionUtils.isEmpty(stableItemList) && iteList.size() != stableItemList.size()) {
            throw new IllegalArgumentException("控制评估与固有评估 步骤数量不匹配");
        }

        if (!CollectionUtils.isEmpty(iteList)) {
            RiskPointEvaluationItem stableItem = null;
            for (int i = 0; i < iteList.size(); i++) {
                //控制item
                RiskPointEvaluationItem item = iteList.get(i);
                RiskPointEvaluationItemShowBean bean = new RiskPointEvaluationItemShowBean();
                BeanUtils.copyProperties(item, bean);
                if (item.getRiskLevel() != null) {
                    bean.setRiskLevelName(RiskLevels.findRiskLevelName(item.getRiskLevel()));
                }
                //获取风险辨识评估详情
                List<RiskPointEvaluationDetail> controlDetailList = riskPointEvaluationDetailDao.findByItemId(item.getId());
                //控制detailList
                bean.setDetailList(getPointControlEvaluationDetailList(controlDetailList));

                List<RiskPointEvaluationDetail> stableDetailList = null;
                if (!CollectionUtils.isEmpty(stableItemList)) {
                    //固有item
                    if (item.getStableItemId() != null && control.getSwitchState().intValue() == 1) {
                        Optional<RiskPointEvaluationItem> oei = riskPointEvaluationItemDao.findById(item.getStableItemId());
                        if (oei.isPresent()) {
                            stableItem = oei.get();
                            bean.setStableItemId(stableItem.getId());
                            bean.setStableRiskLevel(stableItem.getRiskLevel());
                            bean.setStableRiskLevelName(RiskLevels.findRiskLevelName(stableItem.getRiskLevel()));
                            stableDetailList = riskPointEvaluationDetailDao.findByItemId(stableItem.getId());
                            //固有detailList
                            bean.setStableDetailList(getPointStableEvaluationDetailList(stableDetailList));
                        }
                    } else {
                        bean.setStableItemId(null);
                    }

                } else {
                    bean.setStableItemId(null);
                }
                itemList.add(bean);
            }
        }
        return itemList;
    }

    private List<RiskPointEvaluationDetailShowBean> getPointControlEvaluationDetailList(List<RiskPointEvaluationDetail> controlDetailList) {
        List<RiskPointEvaluationDetailShowBean> detailList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(controlDetailList)) {
            for (RiskPointEvaluationDetail detail : controlDetailList) {
                RiskPointEvaluationDetailShowBean detailBean = new RiskPointEvaluationDetailShowBean();
                BeanUtils.copyProperties(detail, detailBean);
                //选项名称
                if (detail.getMethodId() != null) {
                    if (detail.getMethodAnalyzeType() != null && detail.getMethodAnalyzeType().intValue() != 2) {
                        Optional<RiskEvaluationAnalyzeMethod> sem = analyzeMethodDao.findById(detail.getMethodId());
                        if (sem.isPresent()) {
                            detailBean.setMethodName(sem.get().getName());
                        } else {
                            //当前配置项查不到 则返回null
                            detailBean.setMethodId(null);
                            detailBean.setMethodName(null);
                        }
                    } else if (detail.getMethodAnalyzeType() != null && detail.getMethodAnalyzeType().intValue() == 2) {
                        //管控措施
                        RiskMeasureTypeNode riskMeasureTypes = riskMeasureTypeService.findAllParentsByChildId(detail.getMethodId());
                        detailBean.setRiskMeasureTypeNode(riskMeasureTypes);
                        LambdaQueryWrapper<RiskHiddenDangerContent> wrapper = new LambdaQueryWrapper<>();
                        wrapper.eq(RiskHiddenDangerContent::getDeleteFlag, DeleteFlag.EFFECTIVE.getCode());
                        wrapper.eq(RiskHiddenDangerContent::getDetailId, detail.getId());
                        List<RiskHiddenDangerContent> riskHiddenDangerContents = riskHiddenDangerContentService.list(wrapper);
                        detailBean.setHiddenDangerContent(riskHiddenDangerContents);
                    }
                }
                //所选指标选项名称
                if (detail.getTargetItemId() != null) {
                    Optional<RiskEvaluationTargetItem> reti = targetItemDao.findById(detail.getTargetItemId());
                    if (reti.isPresent()) {
                        detailBean.setTargetItemName(reti.get().getName());
                        detailBean.setScore(reti.get().getScore());
                    } else {
                        detailBean.setTargetItemName(null);
                        detailBean.setTargetItemId(null);
                    }
                }
                detailList.add(detailBean);
            }
        }
        return detailList;
    }


    private List<RiskPointDetailStableShowBean> getPointStableEvaluationDetailList(List<RiskPointEvaluationDetail> stableDetailList) {
        List<RiskPointDetailStableShowBean> detailList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(stableDetailList)) {
            for (RiskPointEvaluationDetail detail : stableDetailList) {
                RiskPointDetailStableShowBean detailBean = new RiskPointDetailStableShowBean();
                BeanUtils.copyProperties(detail, detailBean);
                //选项名称
                if (detail.getMethodId() != null) {
                    if (detail.getMethodAnalyzeType() != null && detail.getMethodAnalyzeType().intValue() != 2) {
                        Optional<RiskEvaluationAnalyzeMethod> sem = analyzeMethodDao.findById(detail.getMethodId());
                        if (sem.isPresent()) {
                            detailBean.setMethodName(sem.get().getName());
                        } else {
                            //当前配置项查不到 则返回null
                            detailBean.setMethodId(null);
                            detailBean.setMethodName(null);
                        }
                    }
                }
                //所选指标选项名称
                if (detail.getTargetItemId() != null) {
                    Optional<RiskEvaluationTargetItem> reti = targetItemDao.findById(detail.getTargetItemId());
                    if (reti.isPresent()) {
                        detailBean.setTargetItemName(reti.get().getName());
                        detailBean.setScore(reti.get().getScore());
                    } else {
                        detailBean.setTargetItemName(null);
                        detailBean.setTargetItemId(null);
                    }
                }
                detailList.add(detailBean);
            }
        }
        return detailList;
    }


    private Date add6Month(Date date) {
        try {
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);//设置起时间
            cal.add(Calendar.MONTH, 6);
            String ss = SimpleDateFormatCache.getYmd().format(cal.getTime());
            Date parse = SimpleDateFormatCache.getYmd().parse(ss);
            return parse;
        } catch (ParseException e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    private Date getNowDate() {
        try {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String nowdayTime = dateFormat.format(new Date());
            Date nowDate = dateFormat.parse(nowdayTime);
            return nowDate;
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    //获取风险点类型名称 A(B)
    @Override
    public String getPointTypeName(Long pointId) {
        if (pointId == null) {
            return "";
        }
        RiskPoint point = riskPointDao.findById(pointId).orElseThrow(() -> new IllegalArgumentException("风险点不存在"));
        String pointType = "";
        RiskPointType type = riskPointTypeDao.findByCode(point.getType());
        if (type != null) {
            pointType = type.getName();
        }
        if (point.getSubType() != null) {
            RiskPointType sonType = riskPointTypeDao.findByCode(point.getSubType());
            if (sonType != null) {
                pointType = pointType + "(" + sonType.getName() + ")";
            }
        }
        return pointType;
    }

    /**
     * 获取风险分区风险点列表
     *
     * @param riskDistrictId
     * @return
     */
    @Override
    public Page<RiskPointOfDistrictListBean> getPointInDistrictList(Long riskDistrictId, Pageable page) {
        Page<RiskPoint> pointListPage = riskPointDao.getPointInDistrictListByPage(riskDistrictId, page);
        List<RiskPointOfDistrictListBean> list = new ArrayList<>();
        for (RiskPoint point : pointListPage) {
            RiskPointOfDistrictListBean bean = new RiskPointOfDistrictListBean();
            bean.setId(point.getId());
            bean.setName(point.getName());
            bean.setCode(point.getCode());
            bean.setType(point.getType());
            bean.setSubType(point.getSubType());
            //类型名称
            bean.setPointTypeName(getPointTypeName(point.getId()));
            //评估状态 1评估 0未评估
            if (point.getStableRiskLevel() != null || point.getControlRiskLevel() != null) {
                bean.setPointEvaluationState(1);
            } else {
                bean.setPointEvaluationState(0);
            }
            bean.setStableRiskLevel(point.getStableRiskLevel());
            bean.setStableRiskLevelName(RiskLevels.findRiskLevelName(point.getStableRiskLevel()));
            bean.setControlRiskLevel(point.getControlRiskLevel());
            bean.setControlRiskLevelName(RiskLevels.findRiskLevelName(point.getControlRiskLevel()));
            //2.7风险点实时值
            bean.setRealTimeRiskLevel(point.getRealTimeRiskLevel());
            bean.setRealTimeRiskLevelName(RiskLevels.findRiskLevelName(point.getRealTimeRiskLevel()));
            bean.setLastEvaluationDate(point.getLastEvaluationTime());
            //是否有风险评估 按照是否有控制评估判断
            bean.setIsRiskEvalFlag(riskPointEvaluationBusinessDao.getLastPointEvaluation(point.getId(), AnalyzeTypeEnum.CONTROLLABLE.getValue()) != null);
            list.add(bean);
        }
        return new PageImpl<>(list, page, pointListPage.getTotalElements());
    }


    /*
     */
/**
 * 管控-监测点分页
 *
 * @param condition
 * @return
 * @
 *//*

    @Override
    public Page<RiskControPointBean> pageControlList(Pageable pageable, RiskControlSearchBean condition) {
        List<Long> userIds = new ArrayList<>();
        if (condition != null) {
            if (StringUtils.isNotBlank(condition.getResponseUserName())) {
                List<Long> ids = baseUserDao.getIdsByNameLike(condition.getResponseUserName());
                if (!CollectionUtils.isEmpty(ids)) {
                    userIds.addAll(ids);
                } else {
                    return new PageImpl<>(new ArrayList<>(), pageable, 0);
                }
            }
            if (condition.getResponseUserId() != null) {
                userIds.add(condition.getResponseUserId());
            }
        }

        List<RiskPoint> pointList = riskPointDao.getControlPointList(condition.getControlLevelId(), condition.getControlState(), condition.getResponseDepartId());

        Set<Long> pointIdList = pointList.stream().map(RiskPoint::getId).collect(Collectors.toSet());
        Map<Long, Long> evaluationMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(pointIdList)) {
            List<RiskPointEvaluationDto> pointEvaluations = riskPointMapper.getLastEvaluationByPointIdsAndPointAnalyzeType(pointIdList, 1);
            evaluationMap = pointEvaluations.stream().collect(Collectors.toMap(RiskPointEvaluationDto::getPointId, RiskPointEvaluationDto::getId));
        }

        Iterator<RiskPoint> iterator = pointList.iterator();
        List<RiskControPointBean> beanList = new ArrayList<>();
        int flag = 0;
        while (iterator.hasNext()) {
            RiskPoint point = iterator.next();
            if (condition.getDistrictNameOrCode() != null) {
                if (point.getRiskDistrict() == null || (!point.getRiskDistrict().getName().contains(condition.getDistrictNameOrCode()) &&
                        !point.getRiskDistrict().getCode().contains(condition.getDistrictNameOrCode()))) {
                    iterator.remove();
                    flag = 1;
                }
            }
            if (flag == 0) {
                Long evaluationId = evaluationMap.get(point.getId());
                if (evaluationId != null) {
                    List<RiskPointEvaluationDetail> details = null;
                    if (!CollectionUtils.isEmpty(userIds)) {
                        details = riskPointEvaluationDetailDao.findByCondition(evaluationId, condition.getControlLevelId(), condition.getControlState(), condition.getResponseDepartId(), userIds);
                    } else {
                        details = riskPointEvaluationDetailDao.findByConditionNotUserIds(evaluationId, condition.getControlLevelId(), condition.getControlState(), condition.getResponseDepartId());
                    }
                    if (CollectionUtils.isEmpty(details)) {
                        iterator.remove();
                    }
                }
            }
            flag = 0;
        }
        if (pointList.size() == 0) {
            return new PageImpl<>(new ArrayList<>(), pageable, 0);
        } else {
            pointList = pointList.stream()
                    .sorted(Comparator.comparing(RiskPoint::getLastEvaluationTime, Comparator.nullsFirst(Date::compareTo)).reversed()).collect(Collectors.toList());
            List<RiskPoint> pList = PageableUtil.getList(pageable.getPageNumber(), pageable.getPageSize(), pointList);
            for (RiskPoint point : pList) {
                beanList.add(getRiskControPointBean(point));
            }
            return new PageImpl<>(beanList, pageable, pointList.size());
        }
    }
*/

    /**
     * 管控-监测点分页
     *
     * @param condition
     * @return
     * @
     */
    @Override
    public Page<RiskControPointBean> pageControlList(Pageable pageable, RiskControlSearchBean condition) {
        List<RiskControPointBean> beanList = new ArrayList<>();
        //分页获取数据
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<RiskPointDto> page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(pageable.getPageNumber() + 1, pageable.getPageSize());
        //不进行count查询
        page.setSearchCount(false);

        //管控层级code
        final Long controlLevelId = condition.getControlLevelId();
        //管控状态 1,已管控    2,未管控
        final Integer controlState = condition.getControlState();
        //责任单位id
        final Long responseDepartId = condition.getResponseDepartId();
        //只用风险区域的名称
        final String districtNameOrCode = condition.getDistrictNameOrCode();
        //固有风险等级
        final Integer stableRiskLevel = condition.getStableRiskLevel();
        //控制风险等级
        final Integer controlRiskLevel = condition.getControlRiskLevel();
        //风险点名称
        final String riskPointName = condition.getRiskPointName();
        //排查类型
        final Integer troubleshootingType = condition.getTroubleshootingType();


        // 排查人员或岗位
        List<String> executorIds = new ArrayList<>();
        List<Long> checkJobIds = new ArrayList<>();
        if (StringUtils.isNotBlank(condition.getResponseUserName())) {
            executorIds = baseUserDao.findByNameLike(condition.getResponseUserName()).stream().map(String::valueOf).collect(Collectors.toList());
            checkJobIds = bpJobDao.findByNameLike(condition.getResponseUserName()).stream().map(BpJob::getId).collect(Collectors.toList());
            // 系统中无此对象，直接返回空结果
            if (CollectionUtils.isEmpty(executorIds) && CollectionUtils.isEmpty(checkJobIds)) {
                return new PageImpl<>(beanList, pageable, 0);
            }
        }
        List<Long> deptIds = dataAuthService.findDepartIdsByCurUser();
        final String responseUserName = condition.getResponseUserName();
        //无权限直接返回
        if (CollectionUtils.isEmpty(deptIds)) {
            return new PageImpl<>(beanList, pageable, 0);
        }
        IPage<RiskPointDto> pointList = riskPointMapper.getLastEvaluationList(page, controlLevelId, controlState, responseDepartId, districtNameOrCode, deptIds, controlRiskLevel, stableRiskLevel, riskPointName, responseUserName, executorIds, checkJobIds, troubleshootingType);
        long count = riskPointMapper.getLastEvaluationListCount(controlLevelId, controlState, responseDepartId, districtNameOrCode, deptIds, controlRiskLevel, stableRiskLevel, riskPointName, responseUserName, executorIds, checkJobIds, troubleshootingType);
        for (RiskPointDto point : pointList.getRecords()) {
            beanList.add(getRiskControPointBean(point));
        }
        return new PageImpl<>(beanList, pageable, count);
    }

    //point->bean
    private RiskControPointBean getRiskControPointBean(RiskPointDto f) {
        RiskControPointBean bean = new RiskControPointBean();
        bean.setRiskDistrictId(f.getRiskDistrictId());
        bean.setRiskDistrictName(f.getRiskDistrictName());
        //风险点id
        bean.setRiskPointId(f.getId());
        //风险点名称
        bean.setRiskPointName(f.getName());
        //风险点等级
        bean.setRiskLevel(f.getRiskLevel());
        bean.setRiskLevelName(RiskLevels.findRiskLevelName(f.getRiskLevel()));
        //风险点类型名称
        bean.setType(f.getType());
        bean.setSubType(f.getSubType());
        bean.setRiskPointTypeName(getPointTypeName(f.getId()));
        RiskPointEvaluationBusiness evaluation = getLastRiskPointEvaluationBusiness(f.getId(), 1);
        //最近一次分析方法id
        if (evaluation != null) {
            bean.setAnalyzeWayId(evaluation.getAnalyzeWayId());
            Optional<RiskEvaluationAnalyzeWay> rea = analyzeWayDao.findById(evaluation.getAnalyzeWayId());
            //分析方法名称
            rea.ifPresent(riskEvaluationAnalyzeWay -> bean.setAnalyzeWayName(riskEvaluationAnalyzeWay.getName() + "(" + riskEvaluationAnalyzeWay.getCode() + ")"));
            //评估id
            bean.setPointEvaluationId(evaluation.getId());
            //评估时间
            bean.setEvaluationDate(evaluation.getEvaluationDate());
        }
        bean.setControlRiskLevel(f.getControlRiskLevel());
        bean.setControlRiskLevelName(RiskLevels.findRiskLevelName(f.getControlRiskLevel()));
        bean.setStableRiskLevel(f.getStableRiskLevel());
        bean.setStableRiskLevelName(RiskLevels.findRiskLevelName(f.getStableRiskLevel()));
        bean.setResponseDepartId(f.getResponsibleDepartId());
        bean.setResponseDepartName(findDepartName(f.getResponsibleDepartId()));
        return bean;
    }

    protected String findDepartName(Long departId) {
        if (departId == null) {
            return null;
        }
        return departService.findById(departId).getName();
    }

    /**
     * 管控-措施分页
     *
     * @param pageable
     * @param condition
     * @param pointId
     * @return
     */
    @Override
    public RiskPointItemPageBean pagePointEvaluationDetail(Pageable pageable, RiskControlSearchBean condition, Long pointId) {
        RiskPointItemPageBean pageBean = new RiskPointItemPageBean();
        //获取该风险点最近一次控制风险分析方法
        RiskPointEvaluationBusiness evaluation = getLastRiskPointEvaluationBusiness(pointId, 1);
        if (evaluation == null) {
            pageBean.setTotalCount(0);
            return pageBean;
        }
        Optional<RiskEvaluationAnalyzeWay> cor = analyzeWayDao.findById(evaluation.getAnalyzeWayId());
        if (!cor.isPresent()) {
            pageBean.setTotalCount(0);
            return pageBean;
        }
        getItemPageData(pageBean, evaluation, cor.get(), pageable, condition, getTargetItemMap());
        return pageBean;
    }

    @Override
    public RiskControlDetailed getRiskControlDetailedList(Long pointId) {
        RiskPointEvaluationBusiness evaluation = getLastRiskPointEvaluationBusiness(pointId, 1);
        List<AnalyseContent> analyseContents = new ArrayList<>();
        List<Map<Object, Object>> analyseContentList = new ArrayList<>();
        Map<Long, String> methodTitleMap = new HashMap<>();
        if (evaluation != null) {
            List<RiskEvaluationAnalyzeMethod> analyseMethods = getMethodListByAnalyzeWayId(evaluation.getAnalyzeWayId());
            methodTitleMap = getMethodTitles(analyseMethods);
            List<RiskPointEvaluationItem> items = riskPointEvaluationItemDao.findByPointEvaluationItem(evaluation.getId());
            Map<Long, RiskEvaluationTargetItem> targetItemMap = getTargetItemMap();
            if (!CollectionUtils.isEmpty(items)) {
                for (RiskPointEvaluationItem item : items) {
                    Map<Object, Object> analyseContentDetail = new LinkedHashMap<>();
                    List<RiskPointEvaluationDetail> dList = riskPointEvaluationDetailDao.findByItemId(item.getId());
                    AnalyseContent analyseContent = new AnalyseContent();
                    Map<Object, Object> analyseContentMapItem = new LinkedHashMap<>();
                    Long itemId = null;
                    for (RiskPointEvaluationDetail detail : dList) {
                        itemId = detail.getItemId();
                        analyseContentDetail = parseConfigurationValue(methodTitleMap, targetItemMap, detail);
                        if (!CollectionUtils.isEmpty(analyseContentDetail)) {
                            analyseContentMapItem.putAll(analyseContentDetail);
                        }
                    }
                    analyseContent.setItemId(itemId);
                    analyseContent.setContentDetails(analyseContentMapItem);
                    analyseContents.add(analyseContent);
                }
            }
        }
        return RiskControlDetailed.builder().analyseContentList(analyseContents).analyseTitles(methodTitleMap).build();
    }

    private List<RiskEvaluationAnalyzeMethod> getMethodListByAnalyzeWayId(Long analyzeWayId) {
        List<RiskEvaluationAnalyzeMethod> analyseMethods = new ArrayList<>();
        Optional<RiskEvaluationAnalyzeWay> optionalAnalyzeWay = analyzeWayDao.findById(analyzeWayId);
        if (optionalAnalyzeWay.isPresent()) {
            RiskEvaluationAnalyzeWay analyzeWay = optionalAnalyzeWay.get();
            analyseMethods = analyzeMethodDao.findByWayId(analyzeWay.getId());
        }
        return analyseMethods;
    }

    @Override
    public ResultBean getRiskPointControl(RiskControlSearchBean searchBean, Long riskPointId) {
        List<RiskPointControlDto> riskPointControlPage = new ArrayList<>();
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<RiskPointControlDto> page =
                new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(searchBean.getPage() + 1, searchBean.getSize());
        page.setSearchCount(false);
        // 排查人员或岗位
        String responseUserName = searchBean.getResponseUserName();
        List<String> userIds = null;
        List<Long> checkJobIds = null;
        if (StringUtils.isNotBlank(responseUserName)) {
            userIds = baseUserDao.findByNameLike(responseUserName).stream().map(String::valueOf).collect(Collectors.toList());
            checkJobIds = bpJobDao.findByNameLike(searchBean.getResponseUserName()).stream().map(BpJob::getId).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(userIds) && CollectionUtils.isEmpty(checkJobIds)) {
                return ResultBean.pageData(riskPointControlPage, 0);
            }
        }
        searchBean.setTenentId(Context.getCurrentTenantId());
        searchBean.setOrgCode(Context.getCompanyCode() + Constant.SQL_LIKE);
        riskPointControlPage = riskPointMapper.getRiskPointControlPage(page, searchBean, riskPointId, userIds, checkJobIds);
        Integer count = riskPointMapper.getRiskPointControlCount(searchBean, riskPointId, userIds, checkJobIds);
        convertDto(riskPointControlPage);
        return ResultBean.pageData(riskPointControlPage, count);
    }

    @Override
    public ResultBean getRiskPointControlForScreenPage(RiskControlSearchBean searchBean) {
        // 获取风险区域下每个风险的点的最新一次评估的评估id
        List<EvaluationDateDto> evaluationDateDtos = riskPointMapper.getAllLastEvaluationIdByriskDistrictId(searchBean.getDistrictId());
        // 按风险点分组，再取最大id,此时map的value中是当前风险点的最后评估时间的评估id。。，但是最大评估时间存在相同有多个的情况
        Map<Long, List<EvaluationDateDto>> evaluationMap = evaluationDateDtos.stream().collect(Collectors.groupingBy(EvaluationDateDto::getPointId));
        // idList即是风险区域下所有风险点的最新一次评估，无重复
        ArrayList<Long> evaluationIdList = new ArrayList<>();
        evaluationMap.forEach((key, value) -> {
            Long tempMaxId = 0L;
            for (EvaluationDateDto evaluationDateDto : value) {
                if (evaluationDateDto.getId() > tempMaxId) {
                    tempMaxId = evaluationDateDto.getId();
                }
            }
            evaluationIdList.add(tempMaxId);
        });
        // 未管控直接返回
        if (CollectionUtils.isEmpty(evaluationIdList)) {
            return ResultBean.defaultSuccessResult();
        }
        // 开始查询
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<RiskPointControlDto> page =
                new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(searchBean.getPage() + 1, searchBean.getSize());
        String responseUserName = searchBean.getResponseUserName();
        List<String> userIds = null;
        if (StringUtils.isNotBlank(responseUserName)) {
            userIds = baseUserDao.findByNameLike(responseUserName).stream().map(String::valueOf).collect(Collectors.toList());
        }
        Long tenentId = Context.getCurrentTenantId();
        String orgCode = Context.getCompanyCode() + Constant.SQL_LIKE;
        page.setSearchCount(false);
        List<RiskPointControlDto> riskPointControlPage = riskPointMapper.getRiskControlChecklistForScreenPage(page, evaluationIdList, tenentId, orgCode);
        Integer count = riskPointMapper.getRiskControlChecklistForScreenCount(evaluationIdList, tenentId, orgCode);
        convertDto(riskPointControlPage);
        return ResultBean.pageData(riskPointControlPage, count);
    }

    /**
     * 查看历史评估记录
     *
     * @param riskPointId
     * @return
     */
    @Override
    public ResultBean getPointHistoryEvaluationData(Long riskPointId, Pageable page) {
        int totalNumber = 0;
        List<RiskPointEvaluationBusiness> list = riskPointEvaluationBusinessDao.getHistoryEvaluationData(riskPointId);
        List<PointHistoryEvaluationDataBean> beanList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            totalNumber = list.size();
            list = PageableUtil.getList(page.getPageNumber(), page.getPageSize(), list);
            for (RiskPointEvaluationBusiness business : list) {
                PointHistoryEvaluationDataBean bean = new PointHistoryEvaluationDataBean();
                bean.setRiskEvaluationId(business.getId());
                bean.setEvaluationDate(SimpleDateFormatCache.getYmd().format(business.getEvaluationDate()));
                bean.setEvaluationWayId(business.getAnalyzeWayId());
                Optional<RiskEvaluationAnalyzeWay> raw = analyzeWayDao.findById(business.getAnalyzeWayId());
                if (raw.isPresent()) {
                    bean.setEvaluationWayName(raw.get().getName() + "(" + raw.get().getCode() + ")");
                }
                List<Long> evaluationUserIds = StringUtil.covertJsonToLongList(business.getEvaluationUserIds());
                List<SimpleListBean> evaluationUserBeanList = getEvaluationUserBean(evaluationUserIds);
                if (!CollectionUtils.isEmpty(evaluationUserBeanList)) {
                    bean.setEvaluationUserBeanList(evaluationUserBeanList);
                }
                bean.setRiskLevel(business.getRiskLevel());
                bean.setRiskLevelName(RiskLevels.findRiskLevelName(business.getRiskLevel()));
                beanList.add(bean);
            }
            return ResultBean.pageData(beanList, totalNumber);
        }
        return ResultBean.success(beanList);
    }

    @Override
    public void deleteByPointEvaluationId(Long riskPointEvaluationId) throws ApiBusinessException {
        RiskPointEvaluationBusiness business = riskPointEvaluationBusinessDao.findById(riskPointEvaluationId).orElseThrow(() -> new IllegalArgumentException("评估不存在"));
        // 双预防隐患排查数量
        List<RiskEvaluationRecordDeleteCheckVO> result = checkInvestigatePlan(riskPointEvaluationId);
        if (!CollectionUtils.isEmpty(result)) {
            throw new ApiBusinessException(Status.DELETE_CHECK_FAILED.getCode(), JSONObject.toJSONString(result));
        }

        RiskPoint point = riskPointDao.findById(business.getPointId()).orElseThrow(() -> new IllegalArgumentException("风险点"));
        RiskPointEvaluationBusiness lastEvaluation = riskPointEvaluationBusinessDao.getLastPointEvaluation(point.getId(), AnalyzeTypeEnum.CONTROLLABLE.getValue());
        if (business.getStableEvaluationId() != null) {
            riskPointEvaluationBusinessDao.deleteById(business.getStableEvaluationId());
            riskPointEvaluationItemDao.deleteByPointEvaluationId(business.getStableEvaluationId());
            List<Long> detailIds = riskPointEvaluationDetailDao.findIdsByPointEvaluationId(business.getStableEvaluationId());
            if (!CollectionUtils.isEmpty(detailIds)) {
                riskPointEvaluationDetailDao.deleteByIds(detailIds);
            }
        }
        riskPointEvaluationBusinessDao.deleteById(riskPointEvaluationId);
        riskPointEvaluationItemDao.deleteByPointEvaluationId(riskPointEvaluationId);
        List<Long> detailIds = riskPointEvaluationDetailDao.findIdsByPointEvaluationId(riskPointEvaluationId);
        if (!CollectionUtils.isEmpty(detailIds)) {
            riskPointEvaluationDetailDao.deleteByIds(detailIds);
            riskHiddenDangerContentService.removeByDetailIds(detailIds);
        }
        RiskPointEvaluationBusiness lastContralEvaluation = riskPointEvaluationBusinessDao.getLastPointEvaluation(point.getId(), AnalyzeTypeEnum.CONTROLLABLE.getValue());
        RiskPointEvaluationBusiness lastStableEvaluation = null;
        if (lastEvaluation != null && business.getId().equals(lastEvaluation.getId()) && point.getRiskDistrict() != null) {
            if (lastContralEvaluation != null) {
                if (lastContralEvaluation.getStableEvaluationId() != null) {
                    Optional<RiskPointEvaluationBusiness> oeb = riskPointEvaluationBusinessDao.findById(lastContralEvaluation.getStableEvaluationId());
                    if (oeb.isPresent()) {
                        lastStableEvaluation = oeb.get();
                    }
                }
                point.setRiskLevel(lastContralEvaluation.getRiskLevel());
                Integer pointRealRiskLevel = recalculatePointRealRiskLevel(point, lastContralEvaluation.getId(), null, ControlRiskLevelType.EFFICIENT.getValue());
                point.setRealTimeRiskLevel(pointRealRiskLevel);
                point.setControlRiskLevel(lastContralEvaluation.getRiskLevel());
                String evaluationUserStr = lastContralEvaluation.getEvaluationUserIds();
                if (StringUtils.isNotBlank(evaluationUserStr)) {
                    List<Long> evaluationUserIds = StringUtil.covertJsonToLongList(evaluationUserStr);
                    point = saveRiskForAssessment(evaluationUserIds, point, lastContralEvaluation.getAnalyzeWayId());
                }

            } else {
                point.setRiskLevel(null);
                point.setRealTimeRiskLevel(null);
                point.setControlRiskLevel(null);
                point.setLastEvaluationTime(null);
            }
            if (lastStableEvaluation != null) {
                point.setStableRiskLevel(lastStableEvaluation.getRiskLevel());
            } else {
                point.setStableRiskLevel(null);
            }
            riskPointDao.save(point);
            //重新计算区域等级
            if (point.getRiskDistrict() != null) {
                editDistrictLevel(point.getRiskDistrict(), point.getRiskDistrict().getRiskLevel(), "风险评估-历史记录");
            }
        }
    }

    private List<RiskEvaluationRecordDeleteCheckVO> checkInvestigatePlan(Long riskPointEvaluationId) {
        List<BpInvestigatePlan> investigatePlans = bpInvestigatePlanService.findByRiskPointEvaluationId(riskPointEvaluationId);
        List<RiskEvaluationRecordDeleteCheckVO> result = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(investigatePlans)) {
            Map<Long, List<BpInvestigatePlan>> map = investigatePlans.stream().filter(item -> item.getRiskPointId() != null).collect(Collectors.groupingBy(BpInvestigatePlan::getRiskPointId));
            Set<Long> riskPointIds = map.keySet();
            List<RiskPoint> riskPoints = riskPointDao.findByIds(riskPointIds);
            if (!CollectionUtils.isEmpty(riskPoints)) {
                Map<Long, List<RiskPoint>> riskPointMap = riskPoints.stream().collect(Collectors.groupingBy(RiskPoint::getId));
                map.forEach((key, value) -> {
                    RiskEvaluationRecordDeleteCheckVO vo = new RiskEvaluationRecordDeleteCheckVO();
                    vo.setRiskPointControlNum(value.size());
                    List<RiskPoint> riskPointList = riskPointMap.get(key);
                    if (!CollectionUtils.isEmpty(riskPointList) && riskPointList.get(0) != null) {
                        RiskPoint riskPoint = riskPointList.get(0);
                        vo.setRiskPointName(riskPoint.getName());
                        vo.setRiskPointCode(riskPoint.getCode());
                    }
                    result.add(vo);
                });
            }
        }
        return result;
    }


    /**
     * 设置未直接查出的属性，如：id -> name, id -> instance
     *
     * @param riskPointControlPage
     */
    private void convertDto(List<RiskPointControlDto> riskPointControlPage) {
        for (RiskPointControlDto riskPointControlDto : riskPointControlPage) {
            if (StringUtils.isNotBlank(riskPointControlDto.getCheckRateDescribe()) && riskPointControlDto.getCheckRateDescribe().contains("日")) {
                riskPointControlDto.setCheckRateDescribe(riskPointControlDto.getCheckRateDescribe().replace("日", "天"));
            }
            // 风险等级
            riskPointControlDto.setRiskLevelName(RiskLevels.findRiskLevelName(riskPointControlDto.getRiskLevelId()));
            if (riskPointControlDto.getStableItemId() != null) {
                Optional<RiskPointEvaluationItem> stableItemOp = riskPointEvaluationItemDao.findById(riskPointControlDto.getStableItemId());
                if (stableItemOp.isPresent()) {
                    riskPointControlDto.setStableRiskLevel(stableItemOp.get().getRiskLevel());
                    riskPointControlDto.setStableRiskLevelName(RiskLevels.findRiskLevelName(stableItemOp.get().getRiskLevel()));
                }
            }
            // 排查人员
            List<Long> executorIds = StringUtil.covertJsonToLongList(riskPointControlDto.getExecutorIds());
            if (!CollectionUtils.isEmpty(executorIds)) {
                List<BaseUser> users = baseUserDao.findAllById(executorIds);
                List<SimpleSelectListBean> simpleUses = new ArrayList<>();
                users.stream().forEach(each -> {
                    SimpleSelectListBean simpleSelectListBean = new SimpleSelectListBean(each.getId(), each.getRealName());
                    simpleUses.add(simpleSelectListBean);
                });
                riskPointControlDto.setExecutors(simpleUses);
            }
            // 岗位
            if (riskPointControlDto.getJobId() != null) {
                riskPointControlDto.setJobName(bpJobDao.getNameById(riskPointControlDto.getJobId()));
            }
            // 管控措施分类
            if (riskPointControlDto.getMeasureTypeId() != null) {
                RiskMeasureTypeNode riskMeasureTypeNode = riskMeasureTypeService.findAllParentsByChildId(riskPointControlDto.getMeasureTypeId());
                riskPointControlDto.setRiskMeasureTypeNode(riskMeasureTypeNode);
            }
            // 责任单位
            if (StringUtils.isNotBlank(riskPointControlDto.getResponsibleDepartIds())) {
                Splitter.on(Constant.SPLIT_COMMA).trimResults().splitToList(riskPointControlDto.getResponsibleDepartIds())
                        .stream().map(Long::new)
                        .forEach(each -> riskPointControlDto.getResponsibleDeparts().add(new SimpleSelectListBean(each, bpDepartDao.findDepartNameById(each))));
            }
            // 管控层级
            if (StringUtils.isNotBlank(riskPointControlDto.getControlLevelCodes())) {
                Long tenentId = Context.getCurrentTenantId();
                String orgCode = Context.getCurrentOrgCode();
                Splitter.on(Constant.SPLIT_COMMA).trimResults().splitToList(riskPointControlDto.getControlLevelCodes())
                        .stream().map(Long::new)
                        .forEach(each -> riskPointControlDto.getControlLevels().add(new SimpleSelectListBean(each, riskControllevelsMapper.findNameByCode(each, tenentId, orgCode))));
            }
            if (!CollectionUtils.isEmpty(riskPointControlDto.getExecutors())) {
                String jobName = "";
                List<Long> userIds = riskPointControlDto.getExecutors().stream().map(SimpleSelectListBean::getValue).collect(Collectors.toList());
                List<Long> jobIds = baseUserDao.findJobByIds(userIds);
                List<BpJob> jobList = bpJobDao.findAllByIds(jobIds);
                if (!CollectionUtils.isEmpty(jobList)) {
                    for (int i = 0; i < jobList.size(); i++) {
                        jobName = jobName + jobList.get(i).getName();
                        if (i != jobList.size() - 1) {
                            jobName = jobName + ",";
                        }
                    }

                }
                riskPointControlDto.setJobName(jobName);
            }

        }
    }

    private Map<Object, Object> parseConfigurationValue(Map<Long, String> methodTitleMap, Map<Long, RiskEvaluationTargetItem> targetItemMap, RiskPointEvaluationDetail detail) {
        Map<Object, Object> analyseContentDetail = new HashMap<>();
        if (ConfigurationItemType.SELECT.getValue().equals(detail.getContentType())) {
            if (detail.getTargetItemId() != null) {
                if (!CollectionUtils.isEmpty(targetItemMap)) {
                    RiskEvaluationTargetItem targetItem = targetItemMap.get(detail.getTargetItemId());
                    if (targetItem != null && methodTitleMap.containsKey(detail.getMethodId())) {
                        analyseContentDetail.put(detail.getMethodId(), targetItem.getName());
                    }
                }
            }
        } else {
            if (methodTitleMap.containsKey(detail.getMethodId())) {
                analyseContentDetail.put(detail.getMethodId(), detail.getContent());
            }
        }
        return analyseContentDetail;
    }

    //获取分页对象
    private RiskPointItemPageBean getItemPageData(RiskPointItemPageBean pageBean, RiskPointEvaluationBusiness evaluation, RiskEvaluationAnalyzeWay analyzeWay, Pageable pageable, RiskControlSearchBean condition, Map<Long, RiskEvaluationTargetItem> targetItemMap) {
        //获取抬头
        RiskPointEvaluationjsonBean jsonBean = getPointTitles(analyzeWay, new RiskPointEvaluationjsonBean(), evaluation.getPointAnalyzeType());
        List<RiskPointEvaluationItem> items = new ArrayList<>();
        if (evaluation.getPointAnalyzeType() != null && evaluation.getPointAnalyzeType().equals(1)) {
            //控制
            items = riskPointEvaluationItemDao.findByPointControlEvaluationItemAndContion(evaluation.getId(), condition.getControlLevelId(), condition.getControlState(), condition.getResponseDepartId(), condition.getResponseUserId());
        } else {
            //固有
            items = riskPointEvaluationItemDao.findByPointEvaluationItem(evaluation.getId());
        }
        pageBean.setTotalCount(items.size());
        if (!CollectionUtils.isEmpty(items)) {
            items = PageableUtil.getList(pageable, items);
            covertItemJsonBean(jsonBean, items, targetItemMap);
        }
        pageBean.setAnalyseTitles(jsonBean.getAnalyseTitles());
        pageBean.setEvalTitles(jsonBean.getEvalTitles());
        pageBean.setContentTitles(jsonBean.getContentTitles());
        pageBean.setItems(jsonBean.getItems());
        return pageBean;
    }

    /**
     * 风险点详情
     *
     * @param pageable
     * @param pointId
     * @return
     */
    @Override
    public RiskPointEvalBean getPointEvaluationDetail(Pageable pageable, Long pointId) {
        RiskPointEvalBean bean = new RiskPointEvalBean();
        //获取该风险点最近一次控制风险分析方法
        RiskPointEvaluationBusiness control = getLastRiskPointEvaluationBusiness(pointId, 1);
        RiskPointEvaluationBusiness stable = getLastRiskPointEvaluationBusiness(pointId, 0);
        List<Long> controlUserIds = new ArrayList<>();
        List<SimpleListBean> controlUserBeanList = new ArrayList<>();
        List<Long> stableUserIds = new ArrayList<>();
        List<SimpleListBean> stableUserBeanList = new ArrayList<>();
        if (control != null && StringUtils.isNotBlank(control.getEvaluationUserIds())) {
            controlUserIds = StringUtil.covertJsonToLongList(control.getEvaluationUserIds());
            controlUserBeanList = getEvaluationUserBean(controlUserIds);
        }
        if (stable != null && StringUtils.isNotBlank(stable.getEvaluationUserIds())) {
            stableUserIds = StringUtil.covertJsonToLongList(stable.getEvaluationUserIds());
            stableUserBeanList = getEvaluationUserBean(stableUserIds);
        }
        Optional<RiskPoint> orp = riskPointDao.findById(pointId);
        if (orp.isPresent()) {
            bean.setPointName(orp.get().getName());
            bean.setPointId(orp.get().getId());
            bean.setPointCode(orp.get().getCode());
        }
        bean.setPointType(getPointTypeName(bean.getPointId()));
        Integer riskLevel;
        List<Long> evaluationUserIds = null;
        List<SimpleListBean> evaluationUserBeanList = null;
        String controlNumber = "";
        Date evaluationDate = null;
        //获取当前风险点固有风险配置
        RiskEvaluationControl pointControl = riskEvaluationControlDao.findByName(BaseConfigCodes.WWYT_RISK_NAME);
        if (pointControl != null && pointControl.getSwitchState() != null && pointControl.getSwitchState().intValue() == 0) {
            //当固有关闭时,详情不显示,等级也不讲固有等级计算在内
            stable = null;
        }
        if (control == null && stable == null) {
            return bean;
        } else if (control != null && stable == null) {
            riskLevel = control.getRiskLevel();
            evaluationUserIds = controlUserIds;
            evaluationUserBeanList = controlUserBeanList;
            controlNumber = control.getControlNumber();
            evaluationDate = control.getEvaluationDate();
        } else if (control == null && stable != null) {
            riskLevel = stable.getRiskLevel();
            evaluationUserIds = stableUserIds;
            evaluationUserBeanList = stableUserBeanList;
            controlNumber = stable.getControlNumber();
            evaluationDate = stable.getEvaluationDate();
        } else {
            if (stable.getEvaluationDate().after(control.getEvaluationDate())) {
                evaluationUserIds = stableUserIds;
                evaluationUserBeanList = stableUserBeanList;
                controlNumber = stable.getControlNumber();
                evaluationDate = stable.getEvaluationDate();
            } else if (stable.getEvaluationDate().before(control.getEvaluationDate()) || stable.getEvaluationDate().equals(control.getEvaluationDate())) {
                evaluationUserIds = controlUserIds;
                evaluationUserBeanList = controlUserBeanList;
                controlNumber = control.getControlNumber();
                evaluationDate = control.getEvaluationDate();
            }
            if (stable.getRiskLevel() < control.getRiskLevel()) {
                riskLevel = control.getRiskLevel();
            } else {
                riskLevel = stable.getRiskLevel();
            }
        }
        bean.setRiskLevel(riskLevel);
        bean.setRiskLevelName(RiskLevels.findRiskLevelName(riskLevel));
        bean.setEvaluationUserIds(evaluationUserIds);
        bean.setEvaluationUserBeanList(evaluationUserBeanList);
        bean.setControlNumber(controlNumber);
        bean.setEvaluationDate(evaluationDate);
        Map<Long, RiskEvaluationTargetItem> targetItemMap = getTargetItemMap();
        //控制风险评估
        if (control != null) {
            bean.setControlAnalyzeWayId(control.getAnalyzeWayId());
            Optional<RiskEvaluationAnalyzeWay> controlWay = analyzeWayDao.findById(control.getAnalyzeWayId());
            if (controlWay.isPresent()) {
                bean.setControlAnalyzeWayName(controlWay.get().getName() + "(" + controlWay.get().getCode() + ")");
                bean.setControlPageBean(getItemPageData(new RiskPointItemPageBean(), control, controlWay.get(), pageable, new RiskControlSearchBean(), targetItemMap));
            }
            bean.setControlRiskLevel(control.getRiskLevel());
            bean.setControlRiskLevelName(RiskLevels.findRiskLevelName(control.getRiskLevel()));
            bean.setControlUserIds(controlUserIds);
            bean.setControlUserBeanList(controlUserBeanList);
            bean.setControlControlNumber(control.getControlNumber());
            bean.setControlEvaluationDate(control.getEvaluationDate());
            if (control.getStableEvaluationId() != null) {
                Optional<RiskPointEvaluationBusiness> srb = riskPointEvaluationBusinessDao.findById(control.getStableEvaluationId());
                if (srb.isPresent()) {
                    bean.setStableRiskLevel(srb.get().getRiskLevel());
                    bean.setStableRiskLevelName(RiskLevels.findRiskLevelName(srb.get().getRiskLevel()));
                }
            }
        }

//        //固有风险评估
//        if (stable != null) {
//            bean.setStableAnalyzeWayId(stable.getAnalyzeWayId());
//            Optional<RiskEvaluationAnalyzeWay> stableWay = analyzeWayDao.findById(stable.getAnalyzeWayId());
//            if (stableWay.isPresent()) {
//                bean.setStableAnalyzeWayName(stableWay.get().getName() + "(" + stableWay.get().getCode() + ")");
//                bean.setStablePageBean(getItemPageData(new RiskPointItemPageBean(), stable, stableWay.get(), pageable, new RiskControlSearchBean(), targetItemMap));
//            }
//            bean.setStableRiskLevel(stable.getRiskLevel());
//            bean.setStableRiskLevelName(RiskLevels.findRiskLevelName(stable.getRiskLevel()));
//            bean.setStableUserIds(stableUserIds);
//            bean.setStableUserBeanList(stableUserBeanList);
//            bean.setStableControlNumber(stable.getControlNumber());
//            bean.setStableEvaluationDate(stable.getEvaluationDate());
//        }
        return bean;
    }

    /**
     * 保存管控措施
     */
    @Override
    public RiskPointEvaluationDetail saveControl(RiskPointControlBean bean) {
        RiskPointEvaluationDetail detail = riskPointEvaluationDetailDao.findById(bean.getId()).orElseThrow(() -> new IllegalArgumentException("管控措施不存在"));
        // List<RiskPointEvaluationDetail> details = riskPointEvaluationDetailDao.findByItemId(bean.getItemId());
        // 管控层级、责任单位、责任人List<Long> ids -->  String
        String levelIds = bean.getControlLevelIds().stream().map(String::valueOf).collect(Collectors.joining(Constant.SPLIT_COMMA));
        String responseDepartIds = bean.getResponseDepartIds().stream().map(String::valueOf).collect(Collectors.joining(Constant.SPLIT_COMMA));
//        String userIds = bean.getResponseUserIds().stream().map(String::valueOf).collect(Collectors.joining(Constant.SPLIT_COMMA));
        detail.setControlLevelIds(levelIds);
        detail.setResponseDepartIds(responseDepartIds);
//        detail.setResponseUserIds(userIds);
        detail.setControlState(2);
        RiskPointEvaluationDetail save = riskPointEvaluationDetailDao.save(detail);
        return save;
    }

    /**
     * 批量管控措施
     *
     * @param bean
     * @return
     */
    @Override
    public void saveListControl(RiskPointControlBean bean) {
        List<Long> detalIds = bean.getIdList();
        if (!CollectionUtils.isEmpty(bean.getResponseDepartIds()) && bean.getResponseDepartIds().size() > 10) {
            throw new IllegalArgumentException(Status.TO_MANY_RESPONSE_DEPART.getMsg());
        }
        for (Long itemId : detalIds) {
            bean.setId(itemId);
            saveControl(bean);
        }
    }


    @Override
    public ResultBean pageScreenPointDetails(Pageable pageable, RiskControlSearchBean condition) {
        ScreenEvalItemBean bean = new ScreenEvalItemBean();
        //获取管控措施抬头
        Map<Long, String> contentTitles = getContentTitles(1);
        List<Long> pointEvaluationList = pointEvaluationList(condition);
        if (CollectionUtils.isEmpty(pointEvaluationList)) {
            return ResultBean.success(bean);
        }
        List<RiskPointEvaluationItem> items = riskPointEvaluationItemDao.pageControlPointItem(pointEvaluationList, condition.getControlLevelId(), condition.getResponseDepartId(), condition.getControlStateList());
        if (CollectionUtils.isEmpty(items)) {
            return ResultBean.success(bean);
        }
        bean.setContentTitles(contentTitles);
        bean.setCount(items.size());
        items = PageableUtil.getList(pageable, items);
        List<ScreenEvalItemDataBean> itemDataBeans = new ArrayList<>();
        covertItemData(items, itemDataBeans);
        bean.setItemDataBeans(itemDataBeans);
        return ResultBean.success(bean);
    }

    private void covertItemData(List<RiskPointEvaluationItem> items, List<ScreenEvalItemDataBean> itemDataBeans) {
        for (RiskPointEvaluationItem item : items) {
            ScreenEvalItemDataBean dataBean = new ScreenEvalItemDataBean();
            dataBean.setRiskPointId(item.getRiskPointId());
            Optional<RiskPoint> rp = riskPointDao.findById(item.getRiskPointId());
            if (!rp.isPresent()) {
                continue;
            }
            RiskPoint riskPoint = rp.get();
            dataBean.setRiskPointName(riskPoint.getName());
            dataBean.setPointTypeName(getPointTypeName(item.getRiskPointId()));
            dataBean.setLevelName(RiskLevels.findRiskLevelName(item.getRiskLevel()));
            Map<Long, String> contents = new HashMap<>();
            //获取风险辨识评估详情
            List<RiskPointEvaluationDetail> dList = riskPointEvaluationDetailDao.findByItemId(item.getId());
            covertDetailData(dList, dataBean, contents);
            dataBean.setContents(contents);
            itemDataBeans.add(dataBean);
        }
    }

    private void covertDetailData(List<RiskPointEvaluationDetail> dList, ScreenEvalItemDataBean dataBean, Map<Long, String> contents) {
        for (RiskPointEvaluationDetail detail : dList) {
            if (detail.getMethodAnalyzeType().equals(2)) {
                if (contents != null && contents.get(detail.getMethodId()) != null) {
                    contents.put(detail.getMethodId(), contents.get(detail.getMethodId()) + "\n" + detail.getContent());
                } else if (contents != null && contents.get(detail.getMethodId()) == null) {
                    contents.put(detail.getMethodId(), detail.getContent());
                }
                //管控措施 分级管控信息取第一个
                if (detail.getResponseUserIds() != null && dataBean.getResPonseUserIds() == null) {
                    List<String> stringUserIds = Splitter.on(Constant.SPLIT_COMMA).trimResults().splitToList(detail.getResponseUserIds());
                    List<Long> userIds = stringUserIds.stream().map(id -> Long.parseLong(id.trim())).collect(Collectors.toList());
                    dataBean.setResPonseUserIds(userIds);
                    List<String> userNames = userIds.stream().map(this::getUserName).collect(Collectors.toList());
                    dataBean.setResPonseUserNames(userNames);
                }
                if (detail.getResponseDepartIds() != null && dataBean.getResPonseDepartIds() == null) {
                    List<String> stringDepartIds = Splitter.on(Constant.SPLIT_COMMA).trimResults().splitToList(detail.getResponseDepartIds());
                    List<Long> departIds = stringDepartIds.stream().map(id -> Long.parseLong(id.trim())).collect(Collectors.toList());
                    dataBean.setResPonseDepartIds(departIds);
                    List<String> departNames = departIds.stream().map(this::getDepartName).collect(Collectors.toList());
                    dataBean.setResPonseDepartNames(departNames);
                }
                if (detail.getControlLevelIds() != null && dataBean.getControlLevelIds() == null) {
                    List<String> stringControlLevelIds = Splitter.on(Constant.SPLIT_COMMA).trimResults().splitToList(detail.getControlLevelIds());
                    List<Long> controlLevelIds = stringControlLevelIds.stream().map(id -> Long.parseLong(id.trim())).collect(Collectors.toList());
                    dataBean.setControlLevelIds(controlLevelIds);
                    List<String> controlLevelNames = controlLevelIds.stream().map(each -> riskControllevelsService.getByCode(each).getName()).collect(Collectors.toList());
                    dataBean.setControlLevelNames(controlLevelNames);
                }
                if (detail.getControlState() != null && dataBean.getControlState() == null) {
                    dataBean.setControlState(detail.getControlState());
                    dataBean.setControlStateName(ControlStatus.findNameByCode(detail.getControlState()));
                }
            }
        }
    }


    @Override
    public ResultBean pageControlPointDetail(Pageable pageable, RiskControlSearchBean condition) {
        List<Long> pointEvaluationList = pointEvaluationList(condition);
        if (CollectionUtils.isEmpty(pointEvaluationList)) {
            return ResultBean.success(new ArrayList<>());
        }
        List<RiskControAnalyzeDetailBean> detailBeanList = new ArrayList<>();
        List<RiskPointEvaluationDetail> detailList = riskPointEvaluationDetailDao.pageControlPointDetail(pointEvaluationList, condition.getControlLevelId(), condition.getResponseDepartId(), condition.getControlStateList());
        if (CollectionUtils.isEmpty(detailList)) {
            return ResultBean.success(new ArrayList<>());
        }
        List<RiskPointEvaluationDetail> dlist = PageableUtil.getList(pageable, detailList);
        detailBeanList = getDetailList(detailBeanList, dlist);
        if (CollectionUtils.isEmpty(detailBeanList)) {
            return ResultBean.success(new ArrayList<>());
        } else {
            return ResultBean.pageData(detailBeanList, detailList.size());
        }
    }

    private List<Long> pointEvaluationList(RiskControlSearchBean condition) {
        List<Long> pointEvaluationList = new ArrayList<>();
        List<RiskPoint> pointAll = new ArrayList<>();
        if (condition.getDistrictId() == null) {
            //获取所有风险点
            pointAll = riskPointDao.getControlRiskPointList(condition.getRiskPointName(), condition.getRiskPointLevel());
        } else {
            pointAll = riskPointDao.getPointInDistrictList(condition.getDistrictId());
        }
        Set<Long> pointIdList = pointAll.stream().map(RiskPoint::getId).collect(Collectors.toSet());
        //获取该风险点最近一次控制风险分析方法
        if (CollectionUtils.isEmpty(pointIdList)) {
            return pointEvaluationList;
        }
        List<RiskPointEvaluationDto> evaluations = riskPointMapper.getLastEvaluationByPointIdsAndPointAnalyzeType(pointIdList, 1);
        pointEvaluationList = evaluations.stream().map(RiskPointEvaluationDto::getId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(pointEvaluationList)) {
            return pointEvaluationList;
        }
        return pointEvaluationList;
    }

    /**
     * 风险点及相关措施详情
     *
     * @param detailBeanList
     * @param detailList
     * @return
     */
    @Override
    public List<RiskControAnalyzeDetailBean> getDetailList(List<RiskControAnalyzeDetailBean> detailBeanList, List<RiskPointEvaluationDetail> detailList) {
        for (RiskPointEvaluationDetail detail : detailList) {
            RiskControAnalyzeDetailBean detailBean = new RiskControAnalyzeDetailBean();
            BeanUtils.copyProperties(detail, detailBean);
            //风险点信息
            if (detail.getRiskPointId() != null) {
                Optional<RiskPoint> byId = riskPointDao.findById(detail.getRiskPointId());
                if (byId.isPresent()) {
                    RiskPoint point = byId.get();
                    detailBean.setRiskPointName(point.getName());
                    detailBean.setRiskPointRiskLevel(point.getRiskLevel());
                    detailBean.setRiskPointRiskLevelName(RiskLevels.findRiskLevelName(point.getRiskLevel()));
                    //危险源 事故后果
                    detailBean.setUnstandardSituationConsequence(point.getUnstandardSituationConsequence());
                    detailBean.setAccidentType(point.getAccidentType());
                    if (StringUtils.isNotBlank(point.getType())) {
                        RiskPointType pt = riskPointTypeDao.findByCode(point.getType());
                        if (pt != null) {
                            detailBean.setRiskPointTypeId(pt.getId());
                            detailBean.setRiskPointTypeName(pt.getName());
                        }
                    }
                }
            }

            //选项名称
            if (detail.getMethodId() != null) {
                if (detail.getMethodAnalyzeType() != null && detail.getMethodAnalyzeType().intValue() != 2) {
                    Optional<RiskEvaluationAnalyzeMethod> sem = analyzeMethodDao.findById(detail.getMethodId());
                    if (sem.isPresent()) {
                        detailBean.setMethodName(sem.get().getName());
                    } else {
                        detailBean.setMethodName(null);
                        detailBean.setMethodId(null);
                    }
                } else if (detail.getMethodAnalyzeType() != null && detail.getMethodAnalyzeType().intValue() == 2) {
                    //管控措施
                    Optional<BaseTypeGroupItem> btg = baseTypeGroupItemDao.findById(detail.getMethodId());
                    if (btg.isPresent()) {
                        detailBean.setMethodName(btg.get().getName());
                    } else {
                        detailBean.setMethodName(null);
                        detailBean.setMethodId(null);
                    }
                }
            }
            //所选指标选项名称
            if (detail.getTargetItemId() != null) {
                Optional<RiskEvaluationTargetItem> reti = targetItemDao.findById(detail.getTargetItemId());
                if (reti.isPresent()) {
                    detailBean.setTargetItemName(reti.get().getName());
                } else {
                    detailBean.setTargetItemId(null);
                    detailBean.setTargetItemName(null);
                }
            }
            //管控层级
            String controlLevelIds = detail.getControlLevelIds();
            if (StringUtils.isNotBlank(controlLevelIds)) {
                // 管控层级code集合（字符串，逗号分割）转化为管控层级名称的List
                List<String> controlLevelNames = Splitter.on(Constant.SPLIT_COMMA).trimResults().splitToList(controlLevelIds)
                        .stream().map(id -> Long.parseLong(id.trim())).map(each -> riskControllevelsService.getByCode(each))
                        .map(RiskControllevels::getName)
                        .collect(Collectors.toList());
                detailBean.setControlLevelNames(controlLevelNames);
            }
            //责任单位
            String responseDepartIds = detail.getResponseDepartIds();
            if (StringUtils.isNotBlank(responseDepartIds)) {
                List<String> departNames = Splitter.on(Constant.SPLIT_COMMA).trimResults().splitToList(responseDepartIds)
                        .stream().map(id -> Long.parseLong(id.trim())).map(this::getDepartName).collect(Collectors.toList());
                detailBean.setResponseDepartNames(departNames);
            }
            //责任人
            String responseUserIds = detail.getResponseUserIds();
            if (StringUtils.isNotBlank(responseUserIds)) {
                List<String> userNames = Splitter.on(Constant.SPLIT_COMMA).trimResults().splitToList(responseUserIds)
                        .stream().map(id -> Long.parseLong(id.trim())).map(this::getUserName).collect(Collectors.toList());
                detailBean.setResponseUserNames(userNames);
            }
            //管控层级状态
            detailBean.setControlState(detail.getControlState());
            detailBean.setControlStateName(ControlStatus.findNameByCode(detail.getControlState()));
            //评估时间
            Optional<RiskPointEvaluationBusiness> ore = pointEvaluationBusinessDao.findById(detail.getPointEvaluationId());
            if (ore.isPresent()) {
                detailBean.setEvaluationDate(ore.get().getEvaluationDate());
            }
            detailBeanList.add(detailBean);

        }
        //排序
        detailBeanList = detailBeanList.stream()
                .sorted(Comparator.comparing(RiskControAnalyzeDetailBean::getEvaluationDate, Comparator.nullsFirst(Date::compareTo)).reversed()).collect(Collectors.toList());
        return detailBeanList;
    }

    //获取管控层级状态名称
    @Override
    public String getControlStateName(Integer controlState) {
        if (controlState == null) {
            return null;
        } else if (controlState.equals(1)) {
            return "未分配";
        } else if (controlState.equals(2)) {
            return "已分配";
        } else if (controlState.equals(3)) {
            return "管控中";
        } else {
            return null;
        }
    }

    //获取部门名称
    private SimpleListBean getv2DepartName(Long departId) {
        SimpleListBean bean = new SimpleListBean();
        if (departId == null) {
            return bean;
        } else {
            Optional<BpDepart> byId = bpDepartDao.findById(departId);
            if (byId.isPresent()) {
                BpDepart depart = byId.get();
                bean.setId(depart.getId());
                bean.setName(depart.getName());
                if (depart.getShowState() == null || depart.getShowState().intValue() != 44) {
                    bean.setName(depart.getName());
                }
                return bean;
            } else {
                return bean;
            }
        }
    }

    //获取部门名称
    @Override
    public String getDepartName(Long departId) {
        if (departId == null) {
            return null;
        } else {
            Optional<BpDepart> byId = bpDepartDao.findById(departId);
            if (byId.isPresent()) {
                return byId.get().getName();
            } else {
                return null;
            }
        }
    }

    //获取人员名称
    @Override
    public String getUserName(Long userId) {
        if (userId == null) {
            return null;
        } else {
            Optional<BaseUser> byId = baseUserDao.findById(userId);
            if (byId.isPresent()) {
                return byId.get().getRealName();
            } else {
                return null;
            }
        }
    }

//todo 导入导出需要调整

    /**
     * 获取管控层级列表
     *
     * @return
     */
    @Override
    public List<SimpleSelectListBean> getControlLevelList() {
        List<SimpleSelectListBean> bList = new ArrayList<>();
        ControlLevels[] values = ControlLevels.values();
        for (ControlLevels r : values) {
            SimpleSelectListBean bean = new SimpleSelectListBean();
            bean.setLabel(r.getName());
            bean.setValue(Long.valueOf(r.getCode()));
            bList.add(bean);
        }
        return bList;
    }

    /**
     * 获取管控状态列表
     *
     * @return
     */
    @Override
    public List<SimpleSelectListBean> getControlStateList() {
        ArrayList<SimpleSelectListBean> list = new ArrayList<>();
        SimpleSelectListBean bean1 = new SimpleSelectListBean();
        bean1.setValue(1L);
        bean1.setLabel("未分配");
        SimpleSelectListBean bean2 = new SimpleSelectListBean();
        bean2.setValue(2L);
        bean2.setLabel("已分配");
        list.add(bean1);
        list.add(bean2);
        return list;
    }

    /**
     * 风险评估前段显示
     *
     * @param bean
     * @return
     */

    @Override
    public RiskDistrictEvalBean editDistrictEvaluation(RiskEditDistrictEvaluationBean bean) {
        RiskDistrictEvalBean evalBean = new RiskDistrictEvalBean();
        Integer ruleLevel = null;
        Integer stableRiskLevel = null;
        //获取当前开关配置
        //RiskEvaluationControl stableCont = riskEvaluationControlDao.findByName("区域固有风险评价");
        RiskEvaluationControl ruleCont = riskEvaluationControlDao.findByName("区域风险等级校正");
        RiskEvaluationControl pointCont = riskEvaluationControlDao.findByName(BaseConfigCodes.WWYT_RISK_NAME);
        RiskDistrict district = riskDistrictDao.findById(bean.getRiskDistrictId()).orElseThrow(() -> new IllegalArgumentException("区域不存在"));
        //风险分区 固有风险
        boolean dataFlag = riskEvaluationControlService.getStableEvalFlag();
        if (dataFlag) {
            stableRiskLevel = bean.getDistrictStableLevel();
        }
        if (ruleCont != null && ruleCont.getSwitchState() != null && ruleCont.getSwitchState().intValue() == 1) {
            ruleLevel = bean.getDistrictRuleLevel();
        }

        //风险点评估
        Integer minPointLevel = riskPointDao.getMinPointLevel(bean.getRiskDistrictId());
        if (pointCont != null && pointCont.getSwitchState() != null && pointCont.getSwitchState().intValue() == 0) {
            //风险点固有关闭,找出该区域最低的控制风险等级
            minPointLevel = riskPointDao.getMinControlLevel(bean.getRiskDistrictId());
        }
        //如果区域固有风险 和风险点评估等级为null 则等级校正不参与计算
        if (minPointLevel == null && stableRiskLevel == null) {
            ruleLevel = null;
        }
        Date evalDate = riskPointEvaluationBusinessDao.getLastEvalDateByDistrictId(bean.getRiskDistrictId());
        boolean pointEvalFlag = false;
        if (evalDate != null) {
            pointEvalFlag = true;
        } else {
            if (dataFlag && stableRiskLevel != null) {
                pointEvalFlag = true;
            }
        }
        evalBean.setPointEvalFlag(pointEvalFlag);
        //校正等级 风险点列表等级
        Integer riskLevel = getDistrctRiskLevel(ruleLevel, stableRiskLevel, minPointLevel);
        if (riskLevel == null) {
            riskLevel = district.getStableRiskLevel();
        }
        evalBean.setRiskLevel(riskLevel);
        return evalBean;
    }

    @Override
    public int batchSavePointEvaluation(List<RiskPointEvaluationBusinessBean> evaluationBusinessList, RiskEvaluationExcelMapBean mapBean) {
        Map<Long, RiskDistrictBatchBean> districtMap = new LinkedHashMap<>();
        List<RiskPointBatchEvaluationBean> batchEvaluations = new ArrayList<>();
        List<RiskDistrictBatchBean> riskDistricts = new ArrayList<>();
        List<RiskPoint> listRiskPoint = new ArrayList<>();
        List<BpInvestigatePlan> plans = new ArrayList<>();
        Date date = new Date();
        for (RiskPointEvaluationBusinessBean bean : evaluationBusinessList) {
            Integer shared = bean.getShared();
            if (bean.getShared() != null && shared == 1) {
                if (bean.getEvaluationDate() == null) {
                    bean.setEvaluationDate(date);
                }
                RiskPointEvaluationBusiness business = new RiskPointEvaluationBusiness();

                //保存风险点评估(固有风险/控制风险) 风险点库 控制风险评估
                BeanUtils.copyProperties(bean, business);
                // 评估人员
                if (!CollectionUtils.isEmpty(bean.getEvaluationUserIds())) {
                    business.setEvaluationUserIds(bean.getEvaluationUserIds().stream().map(String::valueOf).collect(Collectors.joining(Constant.SPLIT_COMMA)));
                } else {
                    business.setEvaluationUserIds(null);
                }
                //风险点类别:null风险点;1风险点库
                business.setShared(shared);
                RiskPointEvaluationBusiness pointBusiness = pointEvaluationBusinessDao.save(business);
                //风险点评估值
                String pointEvaluationValue = null;
                //风险辨识评估
                List<RiskPointEvaluationItemAddBean> itemList = bean.getItemList();
                if (!CollectionUtils.isEmpty(itemList)) {
                    int orderNumber = 1;
                    for (RiskPointEvaluationItemAddBean itemAddBean : itemList) {
                        //序号 item
                        itemAddBean.setOrderNumber(orderNumber++);
                        //保存 item
                        RiskPointEvaluationItem pointItem = covertPointEvaluationItem(itemAddBean, bean, pointBusiness.getId(), shared, bean.getPointAnalyzeType());
                        pointItem = riskPointEvaluationItemDao.save(pointItem);
                        List<RiskPointEvaluationDetailAddBean> detailList = itemAddBean.getDetailList();
                        if (!CollectionUtils.isEmpty(detailList)) {
                            //保存 detail
                            batchSaveStorePointEvaluationDetail(shared, bean, pointBusiness.getId(), pointItem.getId(), detailList, pointEvaluationValue);
                        }
                    }
                }
                covertPointData(shared, bean, pointBusiness, pointEvaluationValue, listRiskPoint, batchEvaluations, districtMap);
            } else if (shared == null || shared == 0) {
                if (bean.getEvaluationDate() == null) {
                    bean.setEvaluationDate(date);
                }
                List<RiskPointEvaluationItemAddBean> itemList = bean.getItemList();
                List<RiskPointStableDetailBean> stableDetailList = null;
                //固有评估
                RiskPointEvaluationBusiness stablePointBusiness = null;
                //固有评估item集合
                List<Long> stableItemIds = new ArrayList<>();
                //评估值
                String pointEvaluationValue = null;
                //最近一次控制评估
                RiskPointEvaluationBusiness controLastEvaluation = riskPointEvaluationBusinessDao.getLastPointEvaluation(bean.getPointId(), 1);
                //只导入最近的评估
                boolean lastFlag = true;
                if (controLastEvaluation != null && bean.getEvaluationDate().before(controLastEvaluation.getEvaluationDate())) {
                    lastFlag = false;
                }
                if (!CollectionUtils.isEmpty(itemList)) {
                    stableDetailList = itemList.get(0).getStableDetailList();
                    //固有风险配置
                    RiskEvaluationControl stableConfig = riskEvaluationControlDao.findByName(BaseConfigCodes.WWYT_RISK_NAME);
                    if (stableConfig.getSwitchState() != null && stableConfig.getSwitchState().intValue() == 0) {
                        stableDetailList = null;
                    }
                }
                //固有评估
                if (!CollectionUtils.isEmpty(stableDetailList)) {
                    stablePointBusiness = new RiskPointEvaluationBusiness();
                    //保存风险点评估(固有风险/控制风险) 风险点库 控制风险评估
                    BeanUtils.copyProperties(bean, stablePointBusiness);
                    // 评估人员
                    if (!CollectionUtils.isEmpty(bean.getEvaluationUserIds())) {
                        stablePointBusiness.setEvaluationUserIds(bean.getEvaluationUserIds().stream().map(String::valueOf).collect(Collectors.joining(Constant.SPLIT_COMMA)));
                    } else {
                        stablePointBusiness.setEvaluationUserIds(null);
                    }

                    //风险点类别:null风险点;1风险点库
                    stablePointBusiness.setShared(shared);
                    stablePointBusiness.setPointAnalyzeType(AnalyzeTypeEnum.FIXED.getValue());
                    stablePointBusiness.setRiskLevel(bean.getStableRiskLevel());
                    stablePointBusiness = pointEvaluationBusinessDao.save(stablePointBusiness);
                    if (!CollectionUtils.isEmpty(itemList)) {
                        int orderNumber = 1;
                        for (RiskPointEvaluationItemAddBean itemAddBean : itemList) {
                            //序号 item
                            itemAddBean.setOrderNumber(orderNumber++);
                            //保存 item
                            RiskPointEvaluationItem pointItem = covertPointEvaluationItem(itemAddBean, bean, stablePointBusiness.getId(), shared, AnalyzeTypeEnum.FIXED.getValue());
                            pointItem = riskPointEvaluationItemDao.save(pointItem);
                            stableItemIds.add(pointItem.getId());
                            List<RiskPointStableDetailBean> detailList = itemAddBean.getStableDetailList();
                            if (!CollectionUtils.isEmpty(detailList)) {
                                //保存 detail
                                batchSavePointStableEvaluationDetail(shared, bean, stablePointBusiness.getId(), pointItem.getId(), detailList, pointEvaluationValue);
                            }
                        }
                    }
                }
                //控制评估
                RiskPointEvaluationBusiness controlPointBusiness = new RiskPointEvaluationBusiness();
                //保存风险点评估(固有风险/控制风险) 风险点库 控制风险评估
                BeanUtils.copyProperties(bean, controlPointBusiness);
                // 评估人员
                if (!CollectionUtils.isEmpty(bean.getEvaluationUserIds())) {
                    controlPointBusiness.setEvaluationUserIds(bean.getEvaluationUserIds().stream().map(String::valueOf).collect(Collectors.joining(Constant.SPLIT_COMMA)));
                } else {
                    controlPointBusiness.setEvaluationUserIds(null);
                }
                //风险点类别:null风险点;1风险点库
                controlPointBusiness.setShared(shared);
                controlPointBusiness.setPointAnalyzeType(AnalyzeTypeEnum.CONTROLLABLE.getValue());
                if (stablePointBusiness != null) {
                    controlPointBusiness.setStableEvaluationId(stablePointBusiness.getId());
                }
                controlPointBusiness = pointEvaluationBusinessDao.save(controlPointBusiness);
                //风险辨识评估
                if (!CollectionUtils.isEmpty(itemList)) {
                    int orderNumber = 1;
                    for (int i = 0; i < itemList.size(); i++) {
                        RiskPointEvaluationItemAddBean itemAddBean = itemList.get(i);
                        //序号 item
                        itemAddBean.setOrderNumber(orderNumber++);
                        //保存 item
                        RiskPointEvaluationItem pointItem = covertPointEvaluationItem(itemAddBean, bean, controlPointBusiness.getId(), shared, AnalyzeTypeEnum.CONTROLLABLE.getValue());
                        if (!CollectionUtils.isEmpty(stableItemIds)) {
                            pointItem.setStableItemId(stableItemIds.get(i));
                        }
                        pointItem = riskPointEvaluationItemDao.save(pointItem);
                        List<RiskPointEvaluationDetailAddBean> detailList = itemAddBean.getDetailList();
                        if (!CollectionUtils.isEmpty(detailList)) {
                            //保存 detail
                            batchSavePointControlEvaluationDetail(shared, bean, controlPointBusiness.getId(), pointItem.getId(), detailList, pointEvaluationValue, mapBean, plans, date, lastFlag);
                        }
                    }
                }
                //更新风险点 风险区域 风险区域评估等级
                covertNewPointData(shared, bean, controlPointBusiness, stablePointBusiness, pointEvaluationValue, listRiskPoint, batchEvaluations, districtMap, controLastEvaluation);
            }
        }
        //批量更新风险点信息
        if (!CollectionUtils.isEmpty(listRiskPoint)) {
            riskPointDao.saveAll(listRiskPoint);
            //数据导入完成后，删除风险点下的隐患排查计划
            List<Long> riskPointIds = listRiskPoint.stream().map(r -> r.getId()).collect(Collectors.toList());
            List<Long> riskHiddenDangerContentIds = riskHiddenDangerContentService.findIdsByRiskPoints(riskPointIds);
            if (riskHiddenDangerContentIds != null && !riskHiddenDangerContentIds.isEmpty()) {
                //删除相关计划下的任务
                List<Long> planIds = bpInvestigatePlanService.getPlanIdByContentId(riskHiddenDangerContentIds);
                if (!CollectionUtils.isEmpty(planIds)) {
                    bpInvestigatePlanService.deleteTaskByPlanId(planIds);
                }
                bpInvestigatePlanService.updateInitiateStatusByIds(riskHiddenDangerContentIds);

            }
            //保存新的排查计划
            if (!CollectionUtils.isEmpty(plans)) {
                bpInvestigatePlanRepository.saveAll(plans);
            }
        }

        //更改风险点评估计划
        if (!CollectionUtils.isEmpty(batchEvaluations)) {
            riskEvaluationPlanService.riskPointBatchReCal(batchEvaluations);
        }
        if (!CollectionUtils.isEmpty(districtMap)) {
            Collection<RiskDistrictBatchBean> collection = districtMap.values();
            Iterator<RiskDistrictBatchBean> iterator = collection.iterator();
            while (iterator.hasNext()) {
                riskDistricts.add(iterator.next());
            }
            this.batchEditDistrictLevel(riskDistricts);
        }
        //更新大屏风险点
        monitorPointDataWebSocketService.getRiskPointCount(Context.getCompanyCode().substring(0, 7), Context.getCurrentTenantId());
        return batchEvaluations.size();
    }


    private void covertNewPointData(Integer shared, RiskPointEvaluationBusinessBean bean, RiskPointEvaluationBusiness controlBusiness, RiskPointEvaluationBusiness stablePointBusiness, String pointEvaluationValue,
                                    List<RiskPoint> listRiskPoint, List<RiskPointBatchEvaluationBean> batchEvaluations, Map<Long, RiskDistrictBatchBean> districtMap, RiskPointEvaluationBusiness controLastEvaluation) {

        Integer oldLevel = null;
        Long pointId = controlBusiness.getPointId();
        Optional<RiskPoint> optionalPoint = riskPointDao.findById(pointId);
        if (optionalPoint.isPresent()) {
            RiskPoint point = optionalPoint.get();
            //获取最后一次控制风险评估
            if (controLastEvaluation == null || !controLastEvaluation.getEvaluationDate().after(bean.getEvaluationDate())) {
                point.setPointEvaluationValue(pointEvaluationValue);
                point.setNextEvaluationDate(add6Month(bean.getEvaluationDate()));
                if (point.getRiskDistrict() != null) {
                    oldLevel = point.getRiskDistrict().getRiskLevel();
                }
                if (stablePointBusiness != null) {
                    point.setStableRiskLevel(stablePointBusiness.getRiskLevel());
                }
                if (controlBusiness != null) {
                    point.setRiskLevel(controlBusiness.getRiskLevel());
                    point.setControlRiskLevel(controlBusiness.getRiskLevel());
                    point.setRealTimeRiskLevel(controlBusiness.getRiskLevel());
                    point.setLastEvaluationTime(controlBusiness.getEvaluationDate());
                }
                //保存评估人
                String evaluatorIdJson = point.getEvaluatorIdJson();
                Map<String, List<Long>> map = new HashMap<>();
                if (StringUtils.isNotBlank(evaluatorIdJson)) {
                    map = (Map) JSONObject.parse(evaluatorIdJson);
                }
                map.put(controlBusiness.getAnalyzeWayId().toString(), bean.getEvaluationUserIds());
                point.setEvaluatorIdJson(JSONArray.toJSONString(map));
                listRiskPoint.add(point);

                if (shared == null) {
                    buildBatchEvaluationAndDistrictMap(point, bean, batchEvaluations, districtMap, controlBusiness, oldLevel);
                }
            }
        }
    }


    private void covertPointData(Integer shared, RiskPointEvaluationBusinessBean bean, RiskPointEvaluationBusiness pointBusiness, String pointEvaluationValue,
                                 List<RiskPoint> listRiskPoint, List<RiskPointBatchEvaluationBean> batchEvaluations, Map<Long, RiskDistrictBatchBean> districtMap) {
        Integer oldLevel = null;
        Long pointId = pointBusiness.getPointId();
        Optional<RiskPoint> optionalPoint = riskPointDao.findById(pointId);
        if (optionalPoint.isPresent()) {
            RiskPoint point = optionalPoint.get();
            //获取最后一次控制风险评估
            RiskPointEvaluationBusiness controLastEvaluation = riskPointEvaluationBusinessDao.getLastPointEvaluation(pointId, 1);
            if (controLastEvaluation == null || !controLastEvaluation.getEvaluationDate().after(bean.getEvaluationDate())) {
                point.setPointEvaluationValue(pointEvaluationValue);
                point.setNextEvaluationDate(add6Month(bean.getEvaluationDate()));
                if (point.getRiskDistrict() != null) {
                    oldLevel = point.getRiskDistrict().getRiskLevel();
                }
                if (bean.getPointAnalyzeType() != null && bean.getPointAnalyzeType() == 0) {
                    point.setStableRiskLevel(bean.getRiskLevel());
                } else if (bean.getPointAnalyzeType() != null && bean.getPointAnalyzeType() == 1) {
                    point.setControlRiskLevel(bean.getRiskLevel());
                }
                if (point.getRiskLevel() == null || (bean.getRiskLevel() != null && bean.getRiskLevel() < point.getRiskLevel())) {
                    point.setRiskLevel(bean.getRiskLevel());
                }

                //最后一次评估日期
                if (point.getLastEvaluationTime() == null || controLastEvaluation == null || bean.getEvaluationDate().after(point.getLastEvaluationTime())) {
                    point.setLastEvaluationTime(bean.getEvaluationDate());
                }
                //保存评估人
                String evaluatorIdJson = point.getEvaluatorIdJson();
                Map<String, List<Long>> map = new HashMap<>();
                if (StringUtils.isNotBlank(evaluatorIdJson)) {
                    map = (Map) JSONObject.parse(evaluatorIdJson);
                }
                map.put(pointBusiness.getAnalyzeWayId().toString(), bean.getEvaluationUserIds());
                point.setEvaluatorIdJson(JSONArray.toJSONString(map));
                listRiskPoint.add(point);
                if (shared == null) {
                    buildBatchEvaluationAndDistrictMap(point, bean, batchEvaluations, districtMap, pointBusiness, oldLevel);
                }
            }
        }
    }

    private void buildBatchEvaluationAndDistrictMap(RiskPoint point, RiskPointEvaluationBusinessBean bean, List<RiskPointBatchEvaluationBean> batchEvaluations,
                                                    Map<Long, RiskDistrictBatchBean> districtMap, RiskPointEvaluationBusiness pointBusiness, Integer oldLevel) {
        RiskPointBatchEvaluationBean batchEvaluation = new RiskPointBatchEvaluationBean();
        batchEvaluation.setRiskPoint(point);
        batchEvaluation.setEvaluationTime(bean.getEvaluationDate());
        batchEvaluations.add(batchEvaluation);
        if (point.getRiskDistrict() != null) {
            RiskDistrictBatchBean riskDistrictBatch = districtMap.get(point.getRiskDistrict().getId());
            if (riskDistrictBatch == null) {
                riskDistrictBatch = new RiskDistrictBatchBean();
                riskDistrictBatch.setOldLevel(oldLevel);
                riskDistrictBatch.setEvalDate(pointBusiness.getEvaluationDate());
                riskDistrictBatch.setRiskDistrict(point.getRiskDistrict());
                riskDistrictBatch.setId(point.getRiskDistrict().getId());
                riskDistrictBatch.setResponsibleDepart(bean.getResponsibleDepart());
                riskDistrictBatch.setResponsibleUsers(bean.getResponsibleUsers());
                districtMap.put(point.getRiskDistrict().getId(), riskDistrictBatch);
            } else {
                if (!riskDistrictBatch.getEvalDate().after(pointBusiness.getEvaluationDate())) {
                    riskDistrictBatch.setOldLevel(oldLevel);
                    riskDistrictBatch.setEvalDate(pointBusiness.getEvaluationDate());
                    riskDistrictBatch.setRiskDistrict(point.getRiskDistrict());
                    riskDistrictBatch.setId(point.getRiskDistrict().getId());
                    riskDistrictBatch.setResponsibleDepart(bean.getResponsibleDepart());
                    riskDistrictBatch.setResponsibleUsers(bean.getResponsibleUsers());
                    districtMap.put(point.getRiskDistrict().getId(), riskDistrictBatch);
                }
            }
        }
    }


    private void batchSaveStorePointEvaluationDetail(Integer shared, RiskPointEvaluationBusinessBean bean,
                                                     Long pointEvaluationId, Long pointEvaluationItemId,
                                                     List<RiskPointEvaluationDetailAddBean> detailList, String pointEvaluationValue) {
        for (RiskPointEvaluationDetailAddBean detailAddBean : detailList) {
            //详情
            RiskPointEvaluationDetail detail = covertEvaluationDetail(shared, detailAddBean, bean, pointEvaluationId, pointEvaluationItemId, pointEvaluationValue);
            riskPointEvaluationDetailDao.save(detail);
        }
    }


    private void batchSavePointStableEvaluationDetail(Integer shared, RiskPointEvaluationBusinessBean bean,
                                                      Long pointEvaluationId, Long pointEvaluationItemId,
                                                      List<RiskPointStableDetailBean> detailList, String pointEvaluationValue) {
        for (RiskPointStableDetailBean detailAddBean : detailList) {
            //详情
            RiskPointEvaluationDetail detail = covertStableEvaluationDetail(shared, detailAddBean, bean, pointEvaluationId, pointEvaluationItemId, pointEvaluationValue);
            riskPointEvaluationDetailDao.save(detail);
        }
    }

    private void batchSavePointControlEvaluationDetail(Integer shared, RiskPointEvaluationBusinessBean bean, Long pointEvaluationId, Long pointEvaluationItemId,
                                                       List<RiskPointEvaluationDetailAddBean> detailList, String pointEvaluationValue, RiskEvaluationExcelMapBean mapBean,
                                                       List<BpInvestigatePlan> plans, Date date, boolean lastFlag) {
        //按管控类型合并管控措施与内容
        List<RiskPointEvaluationDetailAddBean> groupList = new ArrayList<>();
        Map<String, RiskPointEvaluationDetailAddBean> measureContentMap = new LinkedHashMap<>();
        for (RiskPointEvaluationDetailAddBean detailAddBean : detailList) {
            //筛选管控措施类型，对内容进行合并:map key=methodId_content, value =  list of content
            String key = getMeasureContentMap(detailAddBean.getMethodId(), detailAddBean.getContent());
            if (detailAddBean.getMethodAnalyzeType() == 2) {
                RiskPointEvaluationDetailAddBean mBean = measureContentMap.get(key);
                if (mBean == null) {
                    measureContentMap.put(key, detailAddBean);
                } else {
                    if (!CollectionUtils.isEmpty(detailAddBean.getHiddenDangerContent())) {
                        List<RiskHiddenDangerContent> hiddenDangerContent = mBean.getHiddenDangerContent();
                        if (hiddenDangerContent == null) {
                            hiddenDangerContent = new ArrayList<>();
                        }
                        hiddenDangerContent.addAll(detailAddBean.getHiddenDangerContent());
                        mBean.setHiddenDangerContent(hiddenDangerContent);
                    }
                    measureContentMap.put(key, mBean);
                }
            } else {
                //其他类型原样保留
                groupList.add(detailAddBean);
            }
        }
        Set<Map.Entry<String, RiskPointEvaluationDetailAddBean>> entrySet = measureContentMap.entrySet();
        Iterator<Map.Entry<String, RiskPointEvaluationDetailAddBean>> entrys = entrySet.iterator();
        while (entrys.hasNext()) {
            Map.Entry<String, RiskPointEvaluationDetailAddBean> entry = entrys.next();
            groupList.add(entry.getValue());
        }
        for (RiskPointEvaluationDetailAddBean detailAddBean : groupList) {
            //详情
            RiskPointEvaluationDetail detail = covertEvaluationDetail(shared, detailAddBean, bean, pointEvaluationId, pointEvaluationItemId, pointEvaluationValue);
            RiskPointEvaluationDetail saveResult = riskPointEvaluationDetailDao.save(detail);
            // 排查内容
            if (MethodAnalyzeType.CONTROL_MEASURES.getCode().equals(saveResult.getMethodAnalyzeType())) {
                if (detailAddBean.getHiddenDangerContent() != null && !detailAddBean.getHiddenDangerContent().isEmpty()) {
                    List<RiskHiddenDangerContent> contentList = detailAddBean.getHiddenDangerContent();
                    //先照排查内容分组合并
                    // contentList = buildRiskHiddenDangerContent(contentList);
                    contentList.forEach(each -> {
                        RiskHiddenDangerContent hiddenDangerContent = new RiskHiddenDangerContent();
                        BeanUtils.copyProperties(each, hiddenDangerContent);
                        hiddenDangerContent.setDetailId(saveResult.getId());
                        riskHiddenDangerContentService.save(hiddenDangerContent);
                        List<BpInvestigatePlan> planList = batchConvertCheckPlan(hiddenDangerContent, mapBean, bean.getPointName(), date, lastFlag);
                        if (!CollectionUtils.isEmpty(planList)) {
                            plans.addAll(planList);
                        }
                    });
                }
            }
        }
    }

    private String getMeasureContentMap(Long id, String content) {
        return id + "_" + content;
    }

    private List<RiskHiddenDangerContent> buildRiskHiddenDangerContent(List<RiskHiddenDangerContent> contentList) {
        List<RiskHiddenDangerContent> resultContents = new ArrayList<>();
        Map<String, List<RiskHiddenDangerContent>> contentMap = contentList.stream().collect(Collectors.groupingBy(RiskHiddenDangerContent::getContent));
        for (Map.Entry<String, List<RiskHiddenDangerContent>> entry : contentMap.entrySet()) {
            List<RiskHiddenDangerContent> contents = entry.getValue();
            RiskHiddenDangerContent dangerContent = contents.get(0);
            if (contents.size() > 1) {
                for (int i = 1; i < contents.size(); i++) {
                    List<DangerContentExcelBean> excelUserBeans = contents.get(i).getExcelUserBeanList();
                    List<DangerContentExcelBean> excelUserBeanList = dangerContent.getExcelUserBeanList();
                    if (!CollectionUtils.isEmpty(excelUserBeans)) {
                        excelUserBeanList.addAll(excelUserBeans);
                        dangerContent.setExcelUserBeanList(excelUserBeanList);
                    }
                    List<DangerContentExcelBean> excelJobBeans = contents.get(i).getExcelJobBeanList();
                    List<DangerContentExcelBean> excelJobBeanList = dangerContent.getExcelJobBeanList();
                    if (!CollectionUtils.isEmpty(excelJobBeans)) {
                        excelJobBeanList.addAll(excelJobBeans);
                        dangerContent.setExcelJobBeanList(excelJobBeanList);
                    }
                }
            }

            List<DangerContentExcelBean> userList = dangerContent.getExcelUserBeanList();
            List<DangerContentExcelBean> jobList = dangerContent.getExcelJobBeanList();
            //将list拆散 将相同岗位的人员合并,周期等信息取第一个
            Map<Long, RiskJobUserBean> jobUserMap = new LinkedHashMap<>();
            Map<String, RiskExcelPeriodJobBean> periodJobMap = new LinkedHashMap<>();
            if (!CollectionUtils.isEmpty(userList)) {
                for (DangerContentExcelBean excelBean : userList) {
                    String key = getExclePlanKey(excelBean.getFlag(), excelBean.getPeriodUnits(), excelBean.getPeriodDaysList(), excelBean.getPeriodWeekList(), excelBean.getPlanStartTime(), excelBean.getPlanEndTime());
                    RiskExcelPeriodJobBean periodJobBean = periodJobMap.get(key);
                    List<InvestigateUserBean> userBeanList = excelBean.getUserBeanList();
                    List<Long> excelJobIds = userBeanList.stream().map(InvestigateUserBean::getJobId).collect(Collectors.toList());
                    if (periodJobBean == null) {
                        periodJobMap.put(key, new RiskExcelPeriodJobBean(excelJobIds, excelBean.getTroubleshootingType()));
                    } else {
                        List<Long> jobIds = periodJobBean.getJobIds();
                        if (!CollectionUtils.isEmpty(jobIds)) {
                            for (Long jobId : excelJobIds) {
                                if (!jobIds.contains(jobId)) {
                                    jobIds.add(jobId);
                                }
                            }
                            periodJobBean.setTroubleshootingType(excelBean.getTroubleshootingType());
                            periodJobBean.setJobIds(jobIds);
                            periodJobMap.put(key, periodJobBean);
                        } else {
                            periodJobBean.setTroubleshootingType(excelBean.getTroubleshootingType());
                            periodJobBean.setJobIds(excelJobIds);
                            periodJobMap.put(key, periodJobBean);
                        }
                    }

                    for (InvestigateUserBean userBean : userBeanList) {
                        Long jobId = userBean.getJobId();
                        RiskJobUserBean riskJobUserBean = jobUserMap.get(jobId);
                        List<Long> userIds = userBean.getUserIds();
                        String hiddenDangersDesc = userBean.getHiddenDangersDesc();
                        String remark = userBean.getRemark();
                        if (riskJobUserBean != null) {
                            List<Long> returnUserIds = riskJobUserBean.getUserIds();
                            for (Long beanUserIds : userIds) {
                                if (!returnUserIds.contains(beanUserIds)) {
                                    returnUserIds.add(beanUserIds);
                                }
                            }
                            riskJobUserBean.setUserIds(returnUserIds);
                            jobUserMap.put(jobId, riskJobUserBean);
                        } else {
                            riskJobUserBean = new RiskJobUserBean();
                            riskJobUserBean.setHiddenDangersDesc(hiddenDangersDesc);
                            riskJobUserBean.setRemark(remark);
                            riskJobUserBean.setUserIds(userIds);
                            jobUserMap.put(jobId, riskJobUserBean);
                        }
                    }
                }
                if (!CollectionUtils.isEmpty(periodJobMap)) {
                    userList = new ArrayList<>();
                    for (Map.Entry<String, RiskExcelPeriodJobBean> pEntry : periodJobMap.entrySet()) {
                        DangerContentExcelBean excelBean = new DangerContentExcelBean();
                        String key = pEntry.getKey();
                        RiskExcelPeriodJobBean periodJobBean = pEntry.getValue();
                        List<String> keyStr = Splitter.on(Constant.SPLIT_UNDERLINE).trimResults().splitToList(key);
                        Integer flag = Integer.valueOf(keyStr.get(0));
                        String periodUnits = keyStr.get(1);
                        List<Integer> periodDaysList = JSONArray.parseArray(keyStr.get(2), Integer.class);
                        List<String> periodWeekList = JSONArray.parseArray(keyStr.get(3), String.class);
                        excelBean.setFlag(flag);
                        excelBean.setPeriodUnits(periodUnits);
                        excelBean.setPeriodDaysList(periodDaysList);
                        excelBean.setPeriodWeekList(periodWeekList);
                        String startTimeStr = keyStr.get(4);
                        String endTimeStr = keyStr.get(5);
                        if (StringUtils.isNotBlank(startTimeStr)) {
                            try {
                                excelBean.setPlanStartTime(SimpleDateFormatCache.getYmdhms().parse(startTimeStr));
                            } catch (ParseException ignored) {
                            }
                        }
                        if (StringUtils.isNotBlank(endTimeStr)) {
                            try {
                                excelBean.setPlanEndTime(SimpleDateFormatCache.getYmdhms().parse(endTimeStr));
                            } catch (ParseException ignored) {
                            }
                        }
                        excelBean.setTroubleshootingType(periodJobBean.getTroubleshootingType());
                        List<InvestigateUserBean> returnUserBeanList = new ArrayList<>();
                        for (Long jobId : periodJobBean.getJobIds()) {
                            InvestigateUserBean userBean = new InvestigateUserBean();
                            RiskJobUserBean riskJobUserBean = jobUserMap.get(jobId);
                            userBean.setRemark(riskJobUserBean.getRemark());
                            userBean.setHiddenDangersDesc(riskJobUserBean.getHiddenDangersDesc());
                            userBean.setJobId(jobId);
                            userBean.setUserIds(riskJobUserBean.getUserIds());
                            returnUserBeanList.add(userBean);
                        }
                        excelBean.setUserBeanList(returnUserBeanList);
                        userList.add(excelBean);
                    }
                    dangerContent.setExcelUserBeanList(userList);
                }
            }


            // 再将同一个key的内容合并  key:flag-周期-频率 value 计划
            Map<String, DangerContentExcelBean> excelUserMap = new LinkedHashMap<>();
            Map<String, DangerContentExcelBean> excelJobMap = new LinkedHashMap<>();
            if (!CollectionUtils.isEmpty(userList)) {
                for (DangerContentExcelBean excelBean : userList) {
                    String key = getExclePlanKey(excelBean.getFlag(), excelBean.getPeriodUnits(), excelBean.getPeriodDaysList(), excelBean.getPeriodWeekList(), excelBean.getPlanStartTime(), excelBean.getPlanEndTime());
                    DangerContentExcelBean resultBean = excelUserMap.get(key);
                    if (resultBean == null) {
                        excelUserMap.put(key, excelBean);
                    } else {
                        //岗位 合并jobid放在同一个周期
                        if (excelBean.getFlag() == 0) {
                            //人员 按照 人员的jobId 合并,去除重复的人员
                            List<InvestigateUserBean> resultUserBeanList = resultBean.getUserBeanList();
                            List<InvestigateUserBean> userBeanList = excelBean.getUserBeanList();
                            if (CollectionUtils.isEmpty(resultUserBeanList) && !CollectionUtils.isEmpty(userBeanList)) {
                                resultUserBeanList = userBeanList;
                            } else if (!CollectionUtils.isEmpty(resultUserBeanList) && !CollectionUtils.isEmpty(userBeanList)) {
                                List<Long> resultJobIds = resultUserBeanList.stream().map(InvestigateUserBean::getJobId).collect(Collectors.toList());
                                Map<Long, InvestigateUserBean> resultUserMap = resultUserBeanList.stream().collect(Collectors.toMap(InvestigateUserBean::getJobId, e -> e));
                                for (InvestigateUserBean userBean : userBeanList) {
                                    if (!resultJobIds.contains(userBean.getJobId())) {
                                        resultJobIds.add(userBean.getJobId());
                                        resultUserBeanList.add(userBean);
                                    } else {
                                        //检查是否有重复人员
                                        InvestigateUserBean resultUserBean = resultUserMap.get(userBean.getJobId());
                                        List<Long> resultIds = resultUserBean.getUserIds();
                                        List<Long> userIds = userBean.getUserIds();
                                        for (Long userId : userIds) {
                                            if (!resultIds.contains(userId)) {
                                                resultIds.add(userId);
                                            }
                                        }
                                        resultUserBean.setUserIds(resultIds);
                                        resultUserMap.put(userBean.getJobId(), resultUserBean);
                                    }
                                }
                            }
                            resultBean.setUserBeanList(resultUserBeanList);
                            excelUserMap.put(key, resultBean);
                        }
                    }
                }
            }
            if (!CollectionUtils.isEmpty(jobList)) {
                for (DangerContentExcelBean excelBean : jobList) {
                    String key = getExclePlanKey(excelBean.getFlag(), excelBean.getPeriodUnits(), excelBean.getPeriodDaysList(), excelBean.getPeriodWeekList(), excelBean.getPlanStartTime(), excelBean.getPlanEndTime());
                    DangerContentExcelBean resultBean = excelJobMap.get(key);
                    if (resultBean == null) {
                        excelJobMap.put(key, excelBean);
                    } else {
                        //岗位 合并jobid放在同一个周期
                        if (excelBean.getFlag() == 1) {
                            List<InvestigateJobBean> resultJobBeanList = resultBean.getJobBeanList();
                            List<InvestigateJobBean> jBeanList = excelBean.getJobBeanList();
                            if (CollectionUtils.isEmpty(resultJobBeanList) && !CollectionUtils.isEmpty(jBeanList)) {
                                resultJobBeanList = jBeanList;
                            } else if (!CollectionUtils.isEmpty(resultJobBeanList) && !CollectionUtils.isEmpty(jBeanList)) {
                                List<Long> resultJobIds = resultJobBeanList.stream().map(InvestigateJobBean::getJobId).collect(Collectors.toList());
                                for (InvestigateJobBean jBean : jBeanList) {
                                    if (!resultJobIds.contains(jBean.getJobId())) {
                                        resultJobIds.add(jBean.getJobId());
                                        resultJobBeanList.add(jBean);
                                    }
                                }
                            }
                            resultBean.setJobBeanList(resultJobBeanList);
                            excelJobMap.put(key, resultBean);
                        }
                    }
                }
            }
            List<DangerContentExcelBean> resultUserList = new ArrayList<>();
            List<DangerContentExcelBean> resultJobrList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(excelUserMap)) {
                for (Map.Entry<String, DangerContentExcelBean> resultEntry : excelUserMap.entrySet()) {
                    DangerContentExcelBean value = resultEntry.getValue();
                    resultUserList.add(value);
                }
            }
            if (!CollectionUtils.isEmpty(excelJobMap)) {
                for (Map.Entry<String, DangerContentExcelBean> resultEntry : excelJobMap.entrySet()) {
                    DangerContentExcelBean value = resultEntry.getValue();
                    resultJobrList.add(value);
                }
            }
            dangerContent.setExcelUserBeanList(resultUserList);
            dangerContent.setExcelJobBeanList(resultJobrList);
            resultContents.add(dangerContent);
        }
        return resultContents;
    }

    private String getExclePlanKey(Integer flag, String periodUnits, List<Integer> periodDaysList, List<String> periodWeekList, Date startTime, Date endTime) {
        String string = JSON.toJSONString(periodDaysList);
        String weekStr = JSON.toJSONString(periodWeekList);
        String startTimeStr = "";
        String endTimeStr = "";
        if (startTime != null && endTime != null) {
            startTimeStr = SimpleDateFormatCache.getYmdhms().format(startTime);
            endTimeStr = SimpleDateFormatCache.getYmdhms().format(endTime);
        }
        return flag + "_" + periodUnits + "_" + string + "_" + weekStr + "_" + startTimeStr + "_" + endTimeStr;
    }

    private List<BpInvestigatePlan> batchConvertCheckPlan(RiskHiddenDangerContent hiddenDangerContent, RiskEvaluationExcelMapBean mapBean, String pointName, Date date, boolean lastFlag) {
        List<BpInvestigatePlan> plans = new ArrayList<>();
        if (!CollectionUtils.isEmpty(hiddenDangerContent.getExcelUserBeanList())) {
            List<DangerContentExcelBean> userDataList = hiddenDangerContent.getExcelUserBeanList();
            // List<Long> userCheckIds = new ArrayList<>();
            for (DangerContentExcelBean bean : userDataList) {
                Integer flag = bean.getFlag();
                //周期
                String periodUnits = bean.getPeriodUnits();
                //周期频率
                List<Integer> periodDaysList = bean.getPeriodDaysList();
                //周频率
                List<String> periodWeekList = bean.getPeriodWeekList();
                //排查类型
                Long troubleshootingType = bean.getTroubleshootingType();
                //周期开始时间
                Date startTime = bean.getPlanStartTime();
                //周期结束时间
                Date endTime = bean.getPlanEndTime();
                List<InvestigateUserBean> userBeanList = bean.getUserBeanList();
                if (!CollectionUtils.isEmpty(userBeanList) && flag == 0) {
                    //多岗位合并
                    InvestigateUserBean userBean = new InvestigateUserBean();
                    List<Long> jobIds = new ArrayList<>();
                    List<Long> userIds = new ArrayList<>();
                    userBeanList.forEach(user -> {
                        userBean.setRemark(user.getRemark());
                        userBean.setHiddenDangersDesc(user.getHiddenDangersDesc());
                        userBean.setJobId(user.getJobId());
                        jobIds.add(user.getJobId());
                        userIds.addAll(user.getUserIds());
                    });
                    userBean.setUserIds(userIds);
                    userBean.setJobIds(jobIds);
                    BpInvestigatePlan plan = builderBasePlanData(periodUnits, periodDaysList, periodWeekList, startTime, endTime, date, hiddenDangerContent.getId(), pointName, mapBean.getJobIdMap(),
                            userBean.getJobId(), userBean.getJobIds(), userBean.getRemark(), userBean.getHiddenDangersDesc(), troubleshootingType, flag, lastFlag);
                    List<Long> userIdList = userBean.getUserIds();//                    Iterator<Long> iterator = userIdList.iterator();
//                    while (iterator.hasNext()) {
//                        Long id = iterator.next();
//                        if (userCheckIds.contains(id)) {
//                            iterator.remove();
//                        } else {
//                            userCheckIds.add(id);
//                        }
//                    }
                    //排查人员
                    if (!CollectionUtils.isEmpty(userIdList)) {
                        plan.setExecutor(JSON.toJSONString(userIdList));
                        plans.add(plan);
                    }
//                    for (InvestigateUserBean userBean : userBeanList) {
//                        BpInvestigatePlan plan = builderBasePlanData(periodUnits, periodDaysList,periodWeekList,startTime,endTime, date, hiddenDangerContent.getId(), pointName, mapBean.getJobIdMap(),
//                                userBean.getJobId(), userBean.getRemark(), userBean.getHiddenDangersDesc(), troubleshootingType, flag, lastFlag);
//                        List<Long> userIds = userBean.getUserIds();
//                        Iterator<Long> iterator = userIds.iterator();
//                        while (iterator.hasNext()) {
//                            Long id = iterator.next();
//                            if (userCheckIds.contains(id)) {
//                                iterator.remove();
//                            } else {
//                                userCheckIds.add(id);
//                            }
//                        }
//                        //排查人员
//                        if (!CollectionUtils.isEmpty(userIds)) {
//                            plan.setExecutor(JSON.toJSONString(userIds));
//                            plans.add(plan);
//                        }
//                    }
                }
            }
        }

        if (!CollectionUtils.isEmpty(hiddenDangerContent.getExcelJobBeanList())) {
            List<DangerContentExcelBean> jobDataList = hiddenDangerContent.getExcelJobBeanList();
            List<Long> jobCheckIds = new ArrayList<>();
            for (DangerContentExcelBean bean : jobDataList) {
                Integer flag = bean.getFlag();
                //周期
                String periodUnits = bean.getPeriodUnits();
                //周期频率
                List<Integer> periodDaysList = bean.getPeriodDaysList();

                List<String> periodWeekList = bean.getPeriodWeekList();
                //周期开始时间
                Date startTime = bean.getPlanStartTime();
                //周期结束时间
                Date endTime = bean.getPlanEndTime();
                //排查类型
                Long troubleshootingType = bean.getTroubleshootingType();
                List<InvestigateJobBean> jobBeanList = bean.getJobBeanList();
                if (!CollectionUtils.isEmpty(jobBeanList) && flag == 1) {
                    for (InvestigateJobBean jobBean : jobBeanList) {
                        BpInvestigatePlan plan = builderBasePlanData(periodUnits, periodDaysList, periodWeekList, startTime, endTime, date, hiddenDangerContent.getId(), pointName, mapBean.getJobIdMap(),
                                jobBean.getJobId(), null, jobBean.getRemark(), jobBean.getHiddenDangersDesc(), troubleshootingType, flag, lastFlag);
                        //岗位
                        Long jobId = jobBean.getJobId();
                        if (!jobCheckIds.contains(jobId)) {
                            jobCheckIds.add(jobId);
                            plan.setUnitId(jobId);
                            plans.add(plan);
                        }
                    }
                }
            }

        }
        return plans;
    }

    private BpInvestigatePlan builderBasePlanData(String periodUnits, List<Integer> periodDaysList, List<String> periodWeekList, Date startTime, Date endTime, Date date, Long hiddenDangerContentId, String pointName,
                                                  Map<Long, String> jobMap, Long jobId, List<Long> jobIds, String remark, String hiddenDangersDesc, Long troubleshootingType, Integer flag, boolean lastFlag) {
        BpInvestigatePlan plan = new BpInvestigatePlan();
        //日期小于最近一次评估日期 禁用,否则启用
        if (lastFlag) {
            plan.setInitiateStatus(PlanStatus.ENABLE.getDesc());
        } else {
            plan.setInitiateStatus(PlanStatus.DISABLE.getDesc());
        }
        //周期
        plan.setPeriodUnit(periodUnits);
        if (periodUnits.equals("天")) {
            if (!CollectionUtils.isEmpty(periodWeekList)) {
                plan.setPeriodUnit("周");
                plan.setPeriodJson(JSON.toJSONString(periodDaysList));
                plan.setCheckRateDescribe(getZhouRateDescribe(periodDaysList));
            } else {
                plan.setPeriodUnit("日");
                plan.setPeriodDays(periodDaysList.get(0));
                plan.setCheckRateDescribe(periodDaysList.get(0) + periodUnits);
            }
        } else {
            plan.setPeriodDays(periodDaysList.get(0));
            plan.setCheckRateDescribe(periodDaysList.get(0) + periodUnits);
        }
        //开始时间
        if (periodUnits.equals("月")) {
            plan.setPlanStartTime(getStartDate(date, "月"));
        } else if (periodUnits.equals("年")) {
            plan.setPlanStartTime(getStartDate(date, "年"));
        } else if (periodUnits.equals("时")) {
            if (startTime != null) {
                plan.setPlanStartTime(startTime);
            } else {
                plan.setPlanStartTime(getStartDate(date, "时"));
            }
            if (endTime != null) {
                plan.setPlanEndTime(endTime);
            }
        } else {
            plan.setPlanStartTime(getStartDate(date, "时"));
        }
        //排查任务id
        plan.setHiddenDangerContentId(hiddenDangerContentId);
        plan.setRiskPointId(riskHiddenDangerContentService.getRiskPointById(hiddenDangerContentId));
        plan.setPointEvaluationId(riskHiddenDangerContentService.getEvaluationIdById(hiddenDangerContentId));
        plan.setCheckRate(PlanCheckRateType.PERIODICITY.getDesc());
        String checkPlanName = pointName + jobMap.get(jobId);
        plan.setCheckPlanName(checkPlanName);
        //多岗位存储
        if (!CollectionUtils.isEmpty(jobIds) && jobIds.size() > 1) {
            plan.setCheckJobJson(JSON.toJSONString(jobIds));
        }
        BpInvestigateType bpInvestigateType = bpInvestigateTypeService.findFirstByCheckType(Constants.RISK_CONTROL_CHECK_TYPE_DEFAULT);
        if (bpInvestigateType == null) {
            bpInvestigateType = bpInvestigatePlanService.saveInvestigateType();
        }
        plan.setCheckJob(jobId);
        plan.setTypeId(bpInvestigateType.getId());
        plan.setTypeName(Constants.RISK_CONTROL_CHECK_TYPE_DEFAULT);
        plan.setSourceType(SourceType.NEW.getValue());
        plan.setRemark(remark);
        plan.setExecutiveUnit(flag);
        plan.setHiddenDangersDesc(hiddenDangersDesc);
        plan.setTroubleshootingType(troubleshootingType);
        return plan;
    }


    public Date getStartDate(Date d, String flag) {
        Calendar c = Calendar.getInstance();
        c.setTime(d);
        //设置为1号,当前日期既为本月第一天
        if (flag.equals("月")) {
            c.set(Calendar.DAY_OF_MONTH, 1);
        } else if (flag.equals("年")) {
            c.set(Calendar.DAY_OF_YEAR, 1);
        }
        //将小时至0
        c.set(Calendar.HOUR_OF_DAY, 0);
        //将分钟至0
        c.set(Calendar.MINUTE, 0);
        //将秒至0
        c.set(Calendar.SECOND, 0);
        //将毫秒至0
        c.set(Calendar.MILLISECOND, 0);
        // 本月第一天的时间戳转换为字符串
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date;
        try {
            date = sdf.parse(sdf.format(new Date(new Long(c.getTimeInMillis()))));
            return date;
        } catch (NumberFormatException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    private String getZhouRateDescribe(List<Integer> periodDaysList) {
        String str = "每";
        for (Integer p : periodDaysList) {
            String unit = getZhouRateDesc(p);
            if (StringUtils.isNotBlank(unit)) {
                str = str + unit + "、";
            }
        }
        if (str.length() > 1) {
            str = str.substring(0, str.length() - 1);
        }
        return str;
    }

    private String getZhouRateDesc(Integer unit) {
        String str = null;
        if (unit != null) {
            switch (unit) {
                case 1:
                    str = "周一";
                    break;
                case 2:
                    str = "周二";
                    break;
                case 3:
                    str = "周三";
                    break;
                case 4:
                    str = "周四";
                    break;
                case 5:
                    str = "周五";
                    break;
                case 6:
                    str = "周六";
                    break;
                case 7:
                    str = "周日";
                    break;
            }
        }
        return str;
    }


    /**
     * 计算风险区域等级
     *
     * @param ruleLevel
     * @param stableRiskLevel
     * @param minPointLevel
     * @return
     */
    private Integer getDistrctRiskLevel(Integer ruleLevel, Integer stableRiskLevel, Integer minPointLevel) {
        Integer level;
        //区域风险点评估等级与区域固有等级取等级较大的
        if (stableRiskLevel == null && minPointLevel != null) {
            level = minPointLevel;
        } else if (stableRiskLevel != null && minPointLevel == null) {
            level = stableRiskLevel;
        } else if (stableRiskLevel != null && minPointLevel != null) {
            if (stableRiskLevel == 2 && minPointLevel <= 3) {
                //区域固有=较大 区域控制>=一般
                level = 1;
            } else if (stableRiskLevel == 3 && minPointLevel == 3) {
                //同为一般升较大
                level = 2;
            } else if (stableRiskLevel < minPointLevel) {
                level = stableRiskLevel;
            } else {
                level = minPointLevel;
            }
        } else {
            level = null;
        }
        //等级校正
        if (level != null && ruleLevel != null) {
            if (level - ruleLevel > 4) {
                level = 4;
            } else if (level - ruleLevel < 1) {
                level = 1;
            } else {
                level = level - ruleLevel;
            }
        } else if (level == null && ruleLevel != null) {
            if (ruleLevel > 4) {
                level = 4;
            } else if (ruleLevel < 1) {
                level = 1;
            } else {
                level = ruleLevel;
            }
        } else if (level != null && ruleLevel == null) {
            if (level > 4) {
                level = 4;
            } else if (level < 1) {
                level = 1;
            }
        } else {
            level = null;
        }
        return level;
    }

    /**
     * 作业风险点评估
     *
     * @param riskEvaluationId 风险点库-风险点id
     * @param riskDistrictId   风险区域id
     * @param flag             0失效;1生效
     * @param workSafetyCode   作业编号
     */
    @Override
    public void changeDistrictLevelFromLibraryPoint(Long riskEvaluationId, Long riskDistrictId, Integer flag, String workSafetyCode) {
        log.info("作业区域风险点集合旧:" + "风险点评估id" + riskEvaluationId + "区域" + riskDistrictId + "作业编码" + flag + workSafetyCode);
        Optional<RiskDistrict> ord = riskDistrictDao.findById(riskDistrictId);
        if (ord.isPresent()) {
            RiskDistrict district = ord.get();
            Integer oldLevel = district.getRiskLevel();
            log.info("作业区域风险点集合旧:" + district.getPointLibraryIdJson());
            Map<String, Long> map = new HashMap<>();
            String idJson = district.getPointLibraryIdJson();
            if (StringUtils.isBlank(idJson)) {
                //旧数据
                district.setDistrictRiskLevel(district.getRiskLevel());
            } else {
                map = (Map) JSONObject.parse(idJson);
            }
            if (flag != null && flag.intValue() == 1) {
                map.put(workSafetyCode, riskEvaluationId);
            } else if (flag != null && flag.intValue() == 0) {
                if (map == null || map.isEmpty()) {
                    return;
                } else {
                    if (map.get(workSafetyCode) != null) {
                        Iterator<String> iterator = map.keySet().iterator();
                        while (iterator.hasNext()) {
                            String key = iterator.next();
                            if (workSafetyCode.equals(key)) {
                                iterator.remove();
                            }
                        }
                    }
                }
            }
            List<Long> idList = map.values().stream().distinct().collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(idList)) {
                district.setPointLibraryIdJson(JSONArray.toJSONString(map));
                district = riskDistrictDao.save(district);
            } else {
                district.setPointLibraryIdJson(null);
                district = riskDistrictDao.save(district);
            }
            //计算区域等级
            editDistrictLevel(district, oldLevel, "作业风险评估");
        }
    }

    /**
     * 区域等级重新计算
     *
     * @param riskDistrict
     * @param oldLevel
     * @param message
     */
    @Override
    public boolean editDistrictLevel(RiskDistrict riskDistrict, Integer oldLevel, String message) {
        boolean riskMessageFlag = false;
        if (riskDistrict == null) {
            return false;
        }
        Integer stableRiskLevel = null;
        RiskEvaluationBusiness business = businessDao.findByRiskDistrictId(riskDistrict.getId());
        String ruleJson = null;
        //获取当前开关配置
        RiskEvaluationControl ruleCont = riskEvaluationControlDao.findByName("区域风险等级校正");
        //RiskEvaluationControl stableCont = riskEvaluationControlDao.findByName("区域固有风险评价");
        if (riskEvaluationControlService.getStableEvalFlag()) {
            stableRiskLevel = riskDistrict.getStableRiskLevel();
        }
        if (business != null && ruleCont != null && ruleCont.getSwitchState() != null && ruleCont.getSwitchState().intValue() == 1) {
            ruleJson = business.getRuleIdJson();
        }
        //校正规则
        Integer ruleLevel = getRuleLevel(ruleJson);
        //风险点评估
        Integer minPointLevel = riskPointDao.getMinControlLevel(riskDistrict.getId());
        riskDistrict.setPointsLevel(minPointLevel);
        //如果区域固有风险 和风险点评估等级为null 则等级校正不参与计算
        if (minPointLevel == null && stableRiskLevel == null) {
            ruleLevel = null;
        }
        riskDistrict.setRuleLevel(ruleLevel);
        //校正等级 风险点列表等级
        riskDistrict = setRuleLevel(riskDistrict);
        //计算区域等级
        Integer level = getDistrctRiskLevel(ruleLevel, stableRiskLevel, minPointLevel);
        riskDistrict.setDistrictRiskLevel(level);
//        if (level != null && oldLevel != null && alarmFlag == 1) {
//            if (level < oldLevel) {
//                //等级升高 产生报警信息
//                evaluationAlarmMessageService.createRiskLevelChangeMessage(riskDistrict.getId(), null, level, oldLevel, message, "评估");
//                riskMessageFlag = true;
//            }
//        }
        if (level == null) {
            level = riskDistrict.getStableRiskLevel();
        }
        riskDistrict.setRiskLevel(level);
        riskDistrictDao.save(riskDistrict);
        editRealDistrictLevel(riskDistrict, riskDistrict.getRealTimeRiskLevel(), getMinPointRealRiskLevel(riskDistrict), message);
        return riskMessageFlag;
    }


    /**
     * 区域实时等级重新计算
     *
     * @param riskDistrict
     * @param oldLevel
     */
    @Override
    public void editRealDistrictLevel(RiskDistrict riskDistrict, Double oldLevel, Integer minPointLevel, String message) {
        if (riskDistrict == null) {
            return;
        }
        List<RiskDynamicRecord> inRecords = riskDynamicRecordMapper.findAllByRiskDistrictIdsAndStatus(Lists.newArrayList(riskDistrict.getId()), 0);
        RiskEvaluationControl dyCont = riskEvaluationControlDao.findByNameAndOrgCodeAndTenentId("动态安全风险评估", riskDistrict.getOrgCode().substring(0, 7), riskDistrict.getTenentId());
        boolean flag = dyCont.getSwitchState().intValue() == 1 && !CollectionUtils.isEmpty(inRecords);
        //当区域刚建立无固有风险 风险点风险和等级矫正 investiageRiskLevel取stableRiskLevel
        Integer investiageRiskLevel = getInvestiageRiskLevel(riskDistrict, minPointLevel);
        if (investiageRiskLevel == null) {
            investiageRiskLevel = riskDistrict.getStableRiskLevel();
        }
        riskDistrict.setInvestiageRiskLevel(investiageRiskLevel);
        if (flag) {
            processingDynamicRiskLevels(riskDistrict, message);
        } else {
            processingJobTicketEvaluationLevels(riskDistrict, oldLevel, message);
        }
    }


    private void processingJobTicketEvaluationLevels(RiskDistrict riskDistrict, Double oldLevel, String message) {
        Integer investiageRiskLevel = riskDistrict.getInvestiageRiskLevel();
        //获取作业风险等级
        Integer workSafetyLevel = getWorkSafetyLevel(riskDistrict);
        if (investiageRiskLevel == null || (workSafetyLevel != null && investiageRiskLevel != null && workSafetyLevel < investiageRiskLevel)) {
            investiageRiskLevel = workSafetyLevel;
        }
        int oldDyLevel = oldLevel.intValue();
        if (oldDyLevel < 1) {
            oldDyLevel = 1;
        }
        if (oldDyLevel > 4) {
            oldDyLevel = 4;
        }
        if (investiageRiskLevel < oldDyLevel) {
            //等级升高 产生报警信息
            evaluationAlarmMessageService.createRiskLevelChangeMessage(riskDistrict.getId(), null, investiageRiskLevel, oldDyLevel, message, "实时");
        }
        riskDistrict.setRealTimeRiskLevel(investiageRiskLevel.doubleValue());
        riskDistrictDao.save(riskDistrict);
        //向大屏推送数据
        monitorPointDataWebSocketService.getDistrictList(Lists.newArrayList(riskDistrict), "UPDATE", riskDistrict.getOrgCode(), riskDistrict.getTenentId());
    }

    private Integer getInvestiageRiskLevel(RiskDistrict riskDistrict, Integer minPointLevel) {
        RiskEvaluationBusiness business = businessDao.findByRiskDistrictId(riskDistrict.getId());
        String ruleJson = null;
        Integer stableRiskLevel = null;
        //RiskEvaluationControl stableCont = riskEvaluationControlDao.findByNameAndOrgCodeAndTenentId("区域固有风险评价", riskDistrict.getOrgCode().substring(0, 7), riskDistrict.getTenentId());
        if (riskEvaluationControlService.getStableEvalFlagByCompany(riskDistrict.getOrgCode().substring(0, 7), riskDistrict.getTenentId())) {
            stableRiskLevel = riskDistrict.getStableRiskLevel();
        }
        RiskEvaluationControl ruleCont = riskEvaluationControlDao.findByNameAndCompany("区域风险等级校正", riskDistrict.getOrgCode(), riskDistrict.getTenentId());
        if (business != null) {
            if (ruleCont != null && ruleCont.getSwitchState() != null && ruleCont.getSwitchState().intValue() == 1) {
                ruleJson = business.getRuleIdJson();
            }
        }
        //校正规则
        Integer ruleLevel = getRuleLevel(ruleJson);
        //如果区域固有风险 和风险点评估等级为null 则等级校正不参与计算
        if (minPointLevel == null && stableRiskLevel == null) {
            ruleLevel = null;
        }
        //计算区域等级
        return getDistrctRiskLevel(ruleLevel, stableRiskLevel, minPointLevel);
    }

    private void processingDynamicRiskLevels(RiskDistrict district, String message) {
        List<RiskDynamicRecord> inRecords = riskDynamicRecordMapper.findAllByRiskDistrictIdsAndStatus(Lists.newArrayList(district.getId()), 0);
        Map<Long, List<RiskDynamicRecord>> inRecordMap = inRecords.stream().collect(Collectors.groupingBy(RiskDynamicRecord::getRiskDistrictId));
        //查询所有参与计算的动态配置
        List<Long> dynamicConfigIds = inRecords.stream().map(RiskDynamicRecord::getDynamicConfigId).distinct().collect(Collectors.toList());
        List<RiskDynamicConfig> configList = riskDynamicConfigDao.findAllById(dynamicConfigIds);
        Map<Long, RiskDynamicConfig> configMap = configList.stream().collect(Collectors.toMap(c -> c.getId(), c -> c));
        List<RiskDynamicRecord> recordList = inRecordMap.get(district.getId());
        Integer workSafetyLevel = getWorkSafetyLevel(district);
        //获取作业风险等级
        Integer oldDyLevel = district.getRealTimeRiskLevel().intValue();
        Double dyRiskLevel = calculateDynamicLevel(district.getInvestiageRiskLevel(), workSafetyLevel, recordList, configMap);
        district.setRealTimeRiskLevel(dyRiskLevel);
        Integer newDyLevel = dyRiskLevel.intValue();
        if (newDyLevel < 1) {
            newDyLevel = 1;
        }
        if (newDyLevel > 4) {
            newDyLevel = 4;
        }
        if (oldDyLevel < 1) {
            oldDyLevel = 1;
        }
        if (oldDyLevel > 4) {
            oldDyLevel = 4;
        }
        if (newDyLevel < oldDyLevel) {
            //等级升高 产生报警信息
            evaluationAlarmMessageService.createRiskLevelChangeMessage(district.getId(), null, newDyLevel, oldDyLevel, message, "动态");
        }
        district.setRealTimeRiskLevel(dyRiskLevel);
        riskDistrictDao.save(district);
        monitorPointDataWebSocketService.getDistrictList(Lists.newArrayList(district), "UPDATE", district.getOrgCode(), district.getTenentId());
    }

    /**
     * 区域动态等级重新计算
     *
     * @param records
     */
    @Override
    public void editDynamicDistrictLevel(List<RiskDynamicRecord> records, String message) {
        if (CollectionUtils.isEmpty(records)) {
            return;
        }
        //将动态记录按照区域id分组
        List<Long> districtIds = records.stream().map(RiskDynamicRecord::getRiskDistrictId).distinct().collect(Collectors.toList());
        List<RiskDistrict> districts = riskDistrictDao.findAllById(districtIds);
        calculateDistrictDynamicLevel(districts, message);
    }

    @Override
    public Long getDistEvalNum() {
        return riskDistrictDao.getDistEvalNum();
    }

    private void calculateDistrictDynamicLevel(List<RiskDistrict> districts, String message) {
        if (CollectionUtils.isEmpty(districts)) {
            return;
        }
        for (RiskDistrict district : districts) {
            //区域排查实时等级不存在 则不参与动态风险计算
            Integer investiageRiskLevel = district.getInvestiageRiskLevel();
            if (district.getRealTimeRiskLevel() == null) {
                log.info("区域动态等级计算: 区域编码s% 实时等级等级为空", district.getCode());
                continue;
            }
            if (investiageRiskLevel == null) {
                log.info("区域动态等级计算: 区域编码s% 排查实时等级为空", district.getCode());
                continue;
            }
            editRealDistrictLevel(district, district.getRealTimeRiskLevel(), getMinPointRealRiskLevel(district), message);
        }
    }


    private Double calculateDynamicLevel(Integer investiageRiskLevel, Integer workSafetyLevel, List<RiskDynamicRecord> recordList, Map<Long, RiskDynamicConfig> configMap) {
        Double level = investiageRiskLevel.doubleValue();
        if (CollectionUtils.isEmpty(recordList)) {
            return level;
        }
        BigDecimal levelDecimal = new BigDecimal(Double.toString(level));
        for (RiskDynamicRecord record : recordList) {
            RiskDynamicConfig config = configMap.get(record.getDynamicConfigId());
            if (config != null) {
                BigDecimal configDecimal = new BigDecimal(Double.toString(config.getScore()));
                levelDecimal = levelDecimal.subtract(configDecimal);
            }
        }
        level = levelDecimal.doubleValue();
        if (workSafetyLevel != null && workSafetyLevel.doubleValue() < level) {
            level = workSafetyLevel.doubleValue();
        }
        return level;
    }


    /**
     * 区域等级批量计算
     *
     * @param districtsBeans
     */
    @Override
    public int batchEditDistrictLevel(List<RiskDistrictBatchBean> districtsBeans) {
        //获取当前开关配置
        boolean stableEvalFlag = riskEvaluationControlService.getStableEvalFlag();
        // RiskEvaluationControl stableCont = riskEvaluationControlDao.findByName("区域固有风险评价");
        RiskEvaluationControl ruleCont = riskEvaluationControlDao.findByName("区域风险等级校正");
        RiskEvaluationControl pointCont = riskEvaluationControlDao.findByName(BaseConfigCodes.WWYT_RISK_NAME);
        //区域各个点的最高风险级别
        List<RiskDistrict> riskDistrictList = new ArrayList<>();
        Set<Long> districtIds = districtsBeans.stream().map(RiskDistrictBatchBean::getRiskDistrict).map(RiskDistrict::getId).collect(Collectors.toSet());

        Map<Long, Integer> fixedDtLevelMap = new HashMap<>();
        Map<Long, Integer> ctrDtLevelMap = new HashMap<>();
        Map<Long, Integer> lastDtLevelMap = new HashMap<>();
        Map<Long, RiskEvaluationBusiness> businessMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(districtIds)) {
            //固定风险
            List<DistrictLevelDto> fixedDtLevels = riskPointMapper.getFixedDistrictMinPointLevel(districtIds);
            fixedDtLevelMap = fixedDtLevels.stream().collect(Collectors.toMap(DistrictLevelDto::getRiskDistrictId, DistrictLevelDto::getRiskLevel));
            //可控风险
            List<DistrictLevelDto> ctrDtLevels = riskPointMapper.getCtrDistrictMinPointLevel(districtIds);
            ctrDtLevelMap = ctrDtLevels.stream().collect(Collectors.toMap(DistrictLevelDto::getRiskDistrictId, DistrictLevelDto::getRiskLevel));
            //区域风险点中最近一次评估风险级别最高的
            List<DistrictLevelDto> lastDtLevels = riskPointMapper.getLastDistrictPointEvaLevel(districtIds, 1);
            lastDtLevelMap = lastDtLevels.stream().collect(Collectors.toMap(DistrictLevelDto::getRiskDistrictId, DistrictLevelDto::getRiskLevel));
            //评估列表
            List<RiskEvaluationBusiness> businessList = businessDao.findByRiskDistrictIdIn(districtIds);
            businessMap = businessList.stream().collect(Collectors.toMap(RiskEvaluationBusiness::getRiskDistrictId, Function.identity()));
        }
        for (RiskDistrictBatchBean each : districtsBeans) {
            RiskDistrict riskDistrict = each.getRiskDistrict();
            Integer oldLevel = each.getOldLevel();
            if (riskDistrict != null) {
                Long districtId = riskDistrict.getId();
                RiskEvaluationBusiness business = businessMap.get(districtId);
                String ruleJson = null;
                Integer stableRiskLevel = null;
                if (business != null) {
                    //风险分区 固有风险
                    if (stableEvalFlag) {
                        stableRiskLevel = riskDistrict.getStableRiskLevel();
                    }
                    if (ruleCont != null && ruleCont.getSwitchState() != null && ruleCont.getSwitchState().equals(1)) {
                        ruleJson = business.getRuleIdJson();
                    }
                }
                //校正规则
                Integer ruleLevel = getRuleLevel(ruleJson);
                //风险点评估
                Integer minPointLevel = fixedDtLevelMap.get(districtId);
                if (pointCont != null && pointCont.getSwitchState() != null && pointCont.getSwitchState().equals(0)) {
                    //风险点固有关闭,找出该区域最低的控制风险等级
                    minPointLevel = ctrDtLevelMap.get(districtId);
                }
                riskDistrict.setPointsLevel(minPointLevel);
                //如果区域固有风险 和风险点评估等级为null 则等级校正不参与计算
                if (minPointLevel == null && stableRiskLevel == null) {
                    ruleLevel = null;
                }
                riskDistrict.setRuleLevel(ruleLevel);
                //校正等级 风险点列表等级
                riskDistrict.setPointsLevel(lastDtLevelMap.get(districtId));
                //设置风险评估状态
                riskDistrict.setEvaluationState(1);
                //计算区域等级
                Integer level = getDistrctRiskLevel(ruleLevel, stableRiskLevel, minPointLevel);
                riskDistrict.setDistrictRiskLevel(level);
//                if (level != null && oldLevel != null) {
//                    if (level < oldLevel) {
//                        //等级升高 产生报警信息
//                        evaluationAlarmMessageService.createRiskLevelChangeMessage(districtId, null, level, oldLevel, "区域风险评估", "评估");
//                    }
//                }
                riskDistrict.setRiskLevel(level);
                //与产品确认 导入评估相当于初始化,不产生报警数据
                riskDistrict.setRealTimeRiskLevel(level.doubleValue());

                if (each.getResponsibleDepart() != null) {
                    riskDistrict.setResponsibleDept(each.getResponsibleDepart());
                }
                if (!CollectionUtils.isEmpty(each.getResponsibleUsers())) {
                    riskDistrict.setResponsibleUser(JSON.toJSONString(each.getResponsibleUsers()));
                }
                riskDistrictList.add(riskDistrict);
            }
        }

        if (!CollectionUtils.isEmpty(riskDistrictList)) {
            List<RiskDistrict> saveList = riskDistrictDao.saveAll(riskDistrictList);
            return saveList.size();
        }
        return 0;
    }

    /**
     * 获取作业风险等级
     *
     * @param riskDistrict
     * @return
     */
    private Integer getWorkSafetyLevel(RiskDistrict riskDistrict) {
        //与作业风险评估比较 取较大的
        String idJson = riskDistrict.getPointLibraryIdJson();
        Integer workSafetyLevel = null;
        if (StringUtils.isNotBlank(idJson)) {
            Map<String, Long> map = (Map) JSONObject.parse(idJson);
            List<Long> idList = map.values().stream().distinct().collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(idList)) {
                workSafetyLevel = pointEvaluationBusinessDao.getLibraryMinPointLevel(idList);
            }
        }
        return workSafetyLevel;
    }

    /**
     * 更新区域等级
     *
     * @param oldRiskDistrictId
     * @param newRiskDistrictId
     */
    @Override
    public void editDistrictEvaluationAndLevel(Long oldRiskDistrictId, Long newRiskDistrictId) {
        if (oldRiskDistrictId == null || newRiskDistrictId == null) {
            return;
        }
        RiskDistrict oldDistrict = riskDistrictDao.findById(oldRiskDistrictId).get();
        RiskDistrict newDistrict = riskDistrictDao.findById(newRiskDistrictId).get();
        editDistrictLevel(oldDistrict, oldDistrict.getRiskLevel(), "区域风险评估");
        editDistrictLevel(newDistrict, newDistrict.getRiskLevel(), "区域风险评估");
    }


    /**
     * 获取最近一次风险点风险评估
     *
     * @param riskPointId           风险点/风险点库 id
     * @param riskPointEvaluationId 作业票-风险点库评估id
     * @param workSafetyDistrictId  作业票中风险点库评估打印-作业票区域id
     * @return
     */
    @Override
    public ResultBean getRiskPointEvaluationJson(Long riskPointId, Long riskPointEvaluationId, Long workSafetyDistrictId) {
        RiskPoint point = riskPointDao.findById(riskPointId).orElse(null);
        if (point == null) {
            return ResultBean.fail(Status.RISK_NOT_EVALUATION);
        }
        RiskPointEvaluationjsonBean bean = new RiskPointEvaluationjsonBean();
        RiskPointEvaluationBusiness controlEvaluationBusiness = null;
        if (riskPointEvaluationId != null) {
            //获取指定的评估内容
            controlEvaluationBusiness = pointEvaluationBusinessDao.findById(riskPointEvaluationId).orElse(null);
            if (controlEvaluationBusiness != null) {
                bean.setRiskLevelName(RiskLevels.findRiskLevelName(controlEvaluationBusiness.getRiskLevel()));
            }
            if (workSafetyDistrictId != null) {
                Optional<RiskDistrict> ord = riskDistrictDao.findById(workSafetyDistrictId);
                if (ord.isPresent()) {
                    bean.setDistrictName(ord.get().getName());
                }
            }
        } else {
            //获取最新的一次控制风险评估
            controlEvaluationBusiness = getLastRiskPointEvaluationBusiness(riskPointId, 1);
            if (point.getRiskLevel() != null) {
                bean.setRiskLevelName(RiskLevels.findRiskLevelName(point.getRiskLevel()));
            }
            if (point.getRiskDistrict() != null) {
                bean.setDistrictName(point.getRiskDistrict().getName());
            }
        }
        if (controlEvaluationBusiness == null || controlEvaluationBusiness.getAnalyzeWayId() == null) {
            return ResultBean.fail(Status.RISK_NOT_EVALUATION);
        }
        bean.setTitle("风险点评价记录");
        bean.setPrintDate(SimpleDateFormatCache.getYmd().format(new Date()));
        bean.setPointName(point.getName());
        bean.setPointCode(point.getCode());
        Optional<RiskEvaluationAnalyzeWay> cor = analyzeWayDao.findById(controlEvaluationBusiness.getAnalyzeWayId());
        if (!cor.isPresent()) {
            return ResultBean.fail(Status.ANALYZE_WAY_NOT_EXIST);
        }
        bean.setControlWayName(cor.get().getName() + "(" + cor.get().getCode() + ")");
        //获取评估内容
        return ResultBean.success(creatPointJsonBean(cor.get(), controlEvaluationBusiness, bean, getTargetItemMap()));
    }

    private Map<Long, RiskEvaluationTargetItem> getTargetItemMap() {
        Map<Long, RiskEvaluationTargetItem> targetItemMap = new HashMap<>();
        List<RiskEvaluationTargetItem> targetItemList = targetItemDao.findAll();
        if (!CollectionUtils.isEmpty(targetItemList)) {
            targetItemMap = targetItemList.stream().collect(Collectors.toMap(r -> r.getId(), r -> r));
        }
        return targetItemMap;
    }

    private RiskPointEvaluationjsonBean creatPointJsonBean(RiskEvaluationAnalyzeWay analyzeWay, RiskPointEvaluationBusiness pointBusiness, RiskPointEvaluationjsonBean bean, Map<Long, RiskEvaluationTargetItem> targetItemMap) {
        //获取分析 评估 管控 标题
        this.getPointTitles(analyzeWay, bean, pointBusiness.getPointAnalyzeType());
        //获取风险辨识评估
        List<RiskPointEvaluationItem> itemList = riskPointEvaluationItemDao.findByPointEvaluationId(pointBusiness.getId());
        covertItemJsonBean(bean, itemList, targetItemMap);
        return bean;
    }

    private void covertItemJsonBean(RiskPointEvaluationjsonBean bean, List<RiskPointEvaluationItem> itemList, Map<Long, RiskEvaluationTargetItem> targetItemMap) {
        if (!CollectionUtils.isEmpty(itemList)) {
            List<RiskPointEvaluationjsonItemBean> items = new ArrayList<>();
            for (int j = 0; j < itemList.size(); j++) {
                RiskPointEvaluationjsonItemBean itemBean = this.getjsonItemBean(itemList, targetItemMap, null, j, null, null);
                items.add(itemBean);
            }
            bean.setItems(items);
        }
    }

    @Override
    public RiskPointEvaluationjsonBean getPointTitles(RiskEvaluationAnalyzeWay analyzeWay, RiskPointEvaluationjsonBean bean, Integer analyzeType) {
        //分析
        List<RiskEvaluationAnalyzeMethod> analyseMethods = analyzeMethodDao.findByWayId(analyzeWay.getId());
        if (!CollectionUtils.isEmpty(analyseMethods)) {
            bean.setAnalyseTitles(this.getMethodTitles(analyseMethods));
        }
        //评估
        if (analyzeWay.getEvaluationId() != null) {
            List<RiskEvaluationAnalyzeMethod> evalMethods = analyzeMethodDao.findByWayIdAndContentType(analyzeWay.getEvaluationId(), 0);
            if (!CollectionUtils.isEmpty(evalMethods)) {
                bean.setEvalTitles(this.getMethodTitles(evalMethods));
            }
        }
        //管控
        bean.setContentTitles(getContentTitles(analyzeType));
        return bean;
    }

    private Map<Long, String> getContentTitles(Integer analyzeType) {
        Map<Long, String> contentTitles = new LinkedHashMap<>();
        if (analyzeType != null && analyzeType.equals(1)) {
            BaseTypeGroup type = baseTypeGroupDao.findByName("管控措施");
            if (type != null) {
                List<BaseTypeGroupItem> cortorList = baseTypeGroupItemDao.findByTypeGroupId(type.getId());
                if (!CollectionUtils.isEmpty(cortorList)) {
                    for (BaseTypeGroupItem item : cortorList) {
                        contentTitles.put(item.getId(), item.getName());
                    }
                }
            }
        }
        return contentTitles;
    }

    private Map<Long, String> getMethodTitles(List<RiskEvaluationAnalyzeMethod> methods) {
        Map<Long, String> titles = new LinkedHashMap<>();
        for (RiskEvaluationAnalyzeMethod method : methods) {
            titles.put(method.getId(), method.getName());
        }
        return titles;
    }

    /**
     * @param itemList
     * @param targetItemMap
     * @param itemDeatilMap
     * @param j             导出 序号
     * @param typeFlag      detail-plan新版本管控-排查
     * @return
     */
    @Override
    public RiskPointEvaluationjsonItemBean getjsonItemBean(List<RiskPointEvaluationItem> itemList, Map<Long, RiskEvaluationTargetItem> targetItemMap, Map<Long, List<RiskPointEvaluationDetail>> itemDeatilMap, int j, ExcelExportToolMapBean toolBean, String typeFlag) {
        RiskPointEvaluationjsonItemBean itemBean = new RiskPointEvaluationjsonItemBean();
        //分析
        Map<Long, String> analyseContent = new LinkedHashMap<>();
        //评估
        Map<Long, String> stableContents = new LinkedHashMap<>();
        //管控
        Map<Long, String> contents = new LinkedHashMap<>();
        List<RiskEvaluationContentDetailBean> contentList = new ArrayList<>();
        itemBean.setIndex(j + 1);
        itemBean.setLevelName(RiskLevels.findRiskLevelName(itemList.get(j).getRiskLevel()));
        RiskPointEvaluationItem controlItem = itemList.get(j);
        if (controlItem.getStableItemId() != null) {
            Optional<RiskPointEvaluationItem> soet = riskPointEvaluationItemDao.findById(controlItem.getStableItemId());
            if (soet.isPresent()) {
                itemBean.setStableLevelName(RiskLevels.findRiskLevelName(soet.get().getRiskLevel()));
            }
        }
        //获取风险辨识评估详情
        List<RiskPointEvaluationDetail> dList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(itemDeatilMap)) {
            dList = itemDeatilMap.get(itemList.get(j).getId());
        } else {
            dList = riskPointEvaluationDetailDao.findByItemId(itemList.get(j).getId());
        }
        if (!CollectionUtils.isEmpty(dList)) {
            for (RiskPointEvaluationDetail detail : dList) {
                if (detail.getMethodAnalyzeType() == null) {
                    continue;
                }
                this.getjsonItemDetailBean(analyseContent, stableContents, contents, detail, itemBean, targetItemMap, toolBean, contentList, typeFlag);
            }
        }
        itemBean.setAnalyseContent(analyseContent);
        itemBean.setStableContents(stableContents);
        itemBean.setContents(contents);
        itemBean.setItemId(itemList.get(j).getId());
        itemBean.setContentList(contentList);
        return itemBean;
    }

    private void getjsonItemDetailBean(Map<Long, String> analyseContent, Map<Long, String> stableContents, Map<Long, String> contents, RiskPointEvaluationDetail detail, RiskPointEvaluationjsonItemBean itemBean, Map<Long, RiskEvaluationTargetItem> targetItemMap, ExcelExportToolMapBean toolBean, List<RiskEvaluationContentDetailBean> contentList, String typeFlag) {
        switch (detail.getMethodAnalyzeType().intValue()) {
            //分析
            case 0:
                if (detail.getContentType() != null && detail.getContentType().equals(1)) {
                    //下拉
                    if (detail.getTargetItemId() != null) {
                        if (!CollectionUtils.isEmpty(targetItemMap)) {
                            RiskEvaluationTargetItem targetItem = targetItemMap.get(detail.getTargetItemId());
                            if (targetItem != null) {
                                analyseContent.put(detail.getMethodId(), targetItem.getName());
                            }
                        }
                    }
                } else {
                    //文本
                    analyseContent.put(detail.getMethodId(), detail.getContent());
                }
                break;
            //评估
            case 1:
                //乘数
                if (detail.getContentType() != null && detail.getContentType().equals(0)) {
                    if (detail.getTargetItemId() != null) {
                        if (!CollectionUtils.isEmpty(targetItemMap)) {
                            RiskEvaluationTargetItem targetItem = targetItemMap.get(detail.getTargetItemId());
                            if (targetItem != null && targetItem.getScore() != null) {
                                stableContents.put(detail.getMethodId(), targetItem.getScore().toString());
                            }
                        }
                    }
                } else {
                    //积
                    if (StringUtils.isNotBlank(detail.getContent())) {
                        stableContents.put(detail.getMethodId(), detail.getContent());
                    }
                }
                break;
            //数据字典
            case 2:
                if (StringUtils.isNotBlank(typeFlag) && typeFlag.equals("detail-plan")) {
                    Map<Long, RiskMeasureType> measureMap = toolBean.getMeasureMap();
                    RiskEvaluationContentDetailBean detailBean = new RiskEvaluationContentDetailBean();
                    detailBean.setContent(detail.getContent());
                    detailBean.setDetailId(detail.getId());
                    if (!CollectionUtils.isEmpty(measureMap)) {
                        RiskMeasureType measureType = measureMap.get(detail.getMethodId());
                        if (measureType != null) {
                            if (measureType.getTypeLevel().equals(3)) {
                                detailBean.setMeasure3(measureType.getMeasureTypeName());
                                RiskMeasureType fMeasureType = measureMap.get(measureType.getParentId());
                                if (fMeasureType != null) {
                                    detailBean.setMeasure2(fMeasureType.getMeasureTypeName());
                                    RiskMeasureType gMeasureType = measureMap.get(fMeasureType.getParentId());
                                    if (gMeasureType != null) {
                                        detailBean.setMeasure1(gMeasureType.getMeasureTypeName());
                                    }
                                }
                            } else if (measureType.getTypeLevel().equals(2)) {
                                detailBean.setMeasure2(measureType.getMeasureTypeName());
                                RiskMeasureType gMeasureType = measureMap.get(measureType.getParentId());
                                if (gMeasureType != null) {
                                    detailBean.setMeasure1(gMeasureType.getMeasureTypeName());
                                }
                            } else if (measureType.getTypeLevel().equals(1)) {
                                detailBean.setMeasure1(measureType.getMeasureTypeName());
                            }
                        }
                    }
                    contentList.add(detailBean);
                } else {
                    //管控措施 分级管控信息取第一个
                    if (!CollectionUtils.isEmpty(contents) && contents.get(detail.getMethodId()) != null) {
                        contents.put(detail.getMethodId(), contents.get(detail.getMethodId()) + "," + detail.getContent());
                    } else if (CollectionUtils.isEmpty(contents) || contents.get(detail.getMethodId()) == null) {
                        contents.put(detail.getMethodId(), detail.getContent());
                    }
                }
                String responseUserIds = detail.getResponseUserIds();
                //typeFlag为空时 考虑评估导出性能 不需要一个个查
                if (StringUtils.isNotBlank(responseUserIds)) {
                    List<Long> userIds = Splitter.on(Constant.SPLIT_COMMA).trimResults().splitToList(responseUserIds)
                            .stream().map(id -> Long.parseLong(id.trim())).collect(Collectors.toList());
                    itemBean.setResponseUserIds(userIds);
                    if (StringUtils.isBlank(typeFlag)) {
                        List<String> userNames = userIds.stream().map(this::getUserName).collect(Collectors.toList());
                        itemBean.setResponseUserNames(userNames);
                    }
                }
                String responseDepartIds = detail.getResponseDepartIds();
                if (StringUtils.isNotBlank(responseDepartIds)) {
                    List<Long> departIds = Splitter.on(Constant.SPLIT_COMMA).trimResults().splitToList(responseDepartIds)
                            .stream().map(id -> Long.parseLong(id.trim())).collect(Collectors.toList());
                    itemBean.setResponseDepartIds(departIds);
                    if (StringUtils.isBlank(typeFlag)) {
                        List<String> departNames = departIds.stream().map(this::getDepartName).collect(Collectors.toList());
                        itemBean.setResponseDepartNames(departNames);
                    }
                }
                String controlLevelIds = detail.getControlLevelIds();
                if (detail.getControlLevelIds() != null) {
                    List<Long> levelIds = Splitter.on(Constant.SPLIT_COMMA).trimResults().splitToList(controlLevelIds)
                            .stream().map(id -> Long.parseLong(id.trim())).collect(Collectors.toList());
                    itemBean.setControlLevelIds(levelIds);
                    if (StringUtils.isBlank(typeFlag)) {
                        List<String> controlLevelNames = levelIds.stream().map(each -> riskControllevelsService.getByCode(each))
                                .map(RiskControllevels::getName).collect(Collectors.toList());
                        itemBean.setControlLevelNames(controlLevelNames);
                    }
                }
                if (detail.getControlState() != null) {
                    itemBean.setControlState(detail.getControlState());
                    itemBean.setControlStateName(ControlStatus.findNameByCode(detail.getControlState()));
                }
                break;
        }
    }

    //获取最近一次评估
    private RiskPointEvaluationBusiness getLastRiskPointEvaluationBusiness(Long riskPointId, Integer analyzeType) {
        return pointEvaluationBusinessDao.getLastPointEvaluation(riskPointId, analyzeType);
    }

    /**
     * 获取区域矫正等级
     *
     * @param json
     * @return
     */
    private Integer getRuleLevel(String json) {
        Integer ruleLevel = null;
        if (StringUtils.isNotBlank(json)) {
            List<Long> ruleList = JSON.parseArray(json, Long.class);
            for (Long id : ruleList) {
                Optional<RiskEvaluationCorrectionRule> byId = correctionRuleDao.findById(id);
                if (byId.isPresent()) {
                    if (byId.get().getLevelChange() != null) {
                        if (ruleLevel == null) {
                            ruleLevel = 0;
                        }
                        ruleLevel = ruleLevel + byId.get().getLevelChange();
                    }
                }
            }
        }
        return ruleLevel;
    }

    //校正等级 风险点列表等级
    private RiskDistrict setRuleLevel(RiskDistrict riskDistrict) {
        List<RiskPoint> points = riskPointDao.findByRiskDistrictId(riskDistrict.getId());
        List<Integer> levelList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(points)) {
            List<Long> collect = points.stream().map(RiskPoint::getId).collect(Collectors.toList());
            for (Long id : collect) {
                RiskPointEvaluationBusiness evaluationBusiness = getLastRiskPointEvaluationBusiness(id, 1);
                if (evaluationBusiness != null) {
                    if (evaluationBusiness.getRiskLevel() != null) {
                        levelList.add(evaluationBusiness.getRiskLevel());
                    }
                }
            }
        }
        if (CollectionUtils.isEmpty(levelList)) {
            riskDistrict.setPointsLevel(null);
        } else {
            riskDistrict.setPointsLevel(Collections.min(levelList));
        }
        return riskDistrict;
    }


    /**
     * 计算实时等级
     *
     * @param flag       0 失效  1有效
     * @param itemRecord 记录
     */
    @Override
    public synchronized void recalculateRealRiskLevel(Integer flag, RiskItemEvalCountRecordVo itemRecord) {
        //产品要求隐患排查不影响动态风险
//        log.warn("计算实时等级: flag={}, itemRecord={}", flag, itemRecord.toString());
//        Optional<RiskPointEvaluationItem> ori = riskPointEvaluationItemDao.findById(itemRecord.getItemId());
//        if (!ori.isPresent()) {
//            log.error("计算实时等级: item {}不存在, 实时等级计算忽略", itemRecord.getItemId());
//            return;
//        }
//        RiskPointEvaluationItem item = ori.get();
//        Optional<RiskPoint> opr = riskPointDao.findById(item.getRiskPointId());
//        if (!opr.isPresent()) {
//            log.error("计算实时等级: 风险点={} 不存在, 实时等级计算忽略", item.getRiskPointId());
//            return;
//        }
//        RiskPointEvaluationBusiness lastPointEvaluation = riskPointEvaluationBusinessDao.getLastPointEvaluation(opr.get().getId(), 1);
//        boolean lastEvalFlag = lastPointEvaluation.getId().equals(item.getPointEvaluationId());
//        Integer count = item.getControlFailureCount();
//        if (count == null) {
//            count = 0;
//        }
//        if (flag.equals(ControlRiskLevelType.INVALID.getValue())) {
//            item.setControlFailureCount(count + 1);
//            itemRecord.setOperation("+1");
//            riskPointEvaluationItemDao.save(item);
//            if (count != null && count.equals(0) && lastEvalFlag) {
//                recalculateDistrictRealTimeRiskLevel(item, flag);
//            }
//        } else if (flag.equals(ControlRiskLevelType.EFFICIENT.getValue())) {
//            item.setControlFailureCount(count - 1);
//            itemRecord.setOperation("-1");
//            if (count - 1 < 0) {
//                itemRecord.setRemark("control_failure_count 不可小于0");
//                log.error("计算实时等级 itemId{} control_failure_count 不可小于0", item.getId());
//                return;
//            }
//            riskPointEvaluationItemDao.save(item);
//            if (count != null && count.equals(1) && lastEvalFlag) {
//                recalculateDistrictRealTimeRiskLevel(item, flag);
//            }
//        }
//        List<RiskItemEvalCountRecord> itemRecords = riskItemEvalCountRecordService.batchCovertRiskItemEvalCountRecord(Lists.newArrayList(itemRecord));
//        if (!CollectionUtils.isEmpty(itemRecords)) {
//            riskItemEvalCountRecordService.saveBatch(itemRecords);
//        }
    }

    //计算区域实时等级
    private void recalculateDistrictRealTimeRiskLevel(RiskPointEvaluationItem controlItem, Integer flag) {
        log.info("计算实时等级 recalculateDistrictRealTimeRiskLevel: flag={}, controlItem id={} ", flag, controlItem.getId());
        Optional<RiskPoint> orp = riskPointDao.findById(controlItem.getRiskPointId());
        if (!orp.isPresent()) {
            return;
        }
        RiskPoint riskPoint = orp.get();
        //获取最近一次控制评估
        RiskPointEvaluationBusiness controlBusiness = getLastRiskPointEvaluationBusiness(riskPoint.getId(), AnalyzeTypeEnum.CONTROLLABLE.getValue());
        if (controlBusiness == null) {
            log.info("计算实时等级 recalculateDistrictRealTimeRiskLevel: controlBusiness= null ,风险点id{} ", riskPoint.getId());
            return;
        }
        if (!controlBusiness.getId().equals(controlItem.getPointEvaluationId())) {
            log.info("计算实时等级 recalculateDistrictRealTimeRiskLevel: 评估id不一致 ");
            return;
        }

        //获取风险点实时评估值
        Integer pointRealRiskLevel = recalculatePointRealRiskLevel(riskPoint, controlItem.getPointEvaluationId(), controlItem.getId(), flag);
        riskPoint.setRealTimeRiskLevel(pointRealRiskLevel);
        riskPointDao.save(riskPoint);
        Integer minPointRiskLevel = getMinPointRealRiskLevel(riskPoint.getRiskDistrict());
        editRealDistrictLevel(riskPoint.getRiskDistrict(), riskPoint.getRiskDistrict().getRealTimeRiskLevel(), minPointRiskLevel, "隐患排查");
    }

    //计算风险点实时等级
    private Integer recalculatePointRealRiskLevel(RiskPoint point, Long pointControlEvaltionId, Long controlItemId, Integer flag) {
        //当前评估最小的步骤等级
        Integer pointRealRiskLevel = null;
        //当前评估最小的控制步骤等级
        Integer controlItemRiskLevel = null;
        //当前评估最小的固有步骤等级
        Integer stableItemRiskLevel = riskPointEvaluationItemDao.getStableMinRiskLevel(pointControlEvaltionId);
        if (flag.equals(ControlRiskLevelType.INVALID.getValue())) {
            controlItemRiskLevel = riskPointEvaluationItemDao.getOtherControlItemRiskLevel(pointControlEvaltionId, controlItemId);
        } else if (flag.equals(ControlRiskLevelType.EFFICIENT.getValue())) {
            controlItemRiskLevel = riskPointEvaluationItemDao.getControlItemRiskLevel(pointControlEvaltionId);
        }
        pointRealRiskLevel = calculateMinLevel(controlItemRiskLevel, stableItemRiskLevel);
        if (pointRealRiskLevel == null && point.getRiskDistrict() != null) {
            pointRealRiskLevel = point.getRiskDistrict().getStableRiskLevel();
        }
        return pointRealRiskLevel;
    }

    @Override
    public void convertUnCheckedRealRiskLevel(List<BpRecordItemBean> uncheckedBeanList) {
        //产品要求隐患排查不影响动态风险
        //key: 评估步骤id value：{ key：排查计划id value：排查记录item id }
//        log.info("风险实时值计算-产生未检 convertUnCheckedRealRiskLevel -start uncheckedBeanList{}", JSON.toJSONString(uncheckedBeanList));
//        Map<Long, Map<Long, Long>> uncheckMap = new HashMap<>();
//        // 获取任务记录item 和 风险评估item 的id映射
//        Set<Long> recordItemIds = uncheckedBeanList.stream().map(BpRecordItemBean::getItemId).collect(Collectors.toSet());
//        List<TaskItemEvaItemMappBean> evaItems = riskDynamicRecordMapper.findEvaItemIdByTaskRecordItemIds(recordItemIds);
//        Map<Long, Long> evaItemsMapping = evaItems.stream().collect(Collectors.toMap(TaskItemEvaItemMappBean::getRecordItemId, TaskItemEvaItemMappBean::getEvaItemId));
//        for (BpRecordItemBean bean : uncheckedBeanList) {
//            // Long evalItemId = bpInvestigateRecordItemDao.getPointEvalItemIdById(bean.getItemId());
//            Long evalItemId = evaItemsMapping.get(bean.getItemId());
//            bean.setEvalItemId(evalItemId);
//            if (evalItemId != null) {
//                Map<Long, Long> planMap = uncheckMap.get(evalItemId);
//                if (CollectionUtils.isEmpty(planMap)) {
//                    planMap = new HashMap<>();
//                    planMap.put(bean.getPlanId(), bean.getItemId());
//                    uncheckMap.put(evalItemId, planMap);
//                } else {
//                    planMap.put(bean.getPlanId(), bean.getItemId());
//                    uncheckMap.put(evalItemId, planMap);
//                }
//            }
//        }
//        List<RiskItemEvalCountRecordVo> recordVos = new ArrayList<>();
//        if (!CollectionUtils.isEmpty(uncheckMap)) {
//            List<RiskPointEvaluationItem> items = riskPointEvaluationItemDao.findByIds(uncheckMap.keySet());
//            Map<Long, RiskPointEvaluationItem> evalMap = items.stream().collect(Collectors.toMap(e -> e.getId(), e -> e));
//            List<RiskPointEvaluationItem> evaluationItemList = new ArrayList<>();
//            // key:风险点id value 评估id集合
//            Map<Long, List<Long>> batchItemMap = new HashMap<>();
//            for (Map.Entry<Long, Map<Long, Long>> entry : uncheckMap.entrySet()) {
//                RiskPointEvaluationItem evaluationItem = evalMap.get(entry.getKey());
////                Optional<RiskPointEvaluationItem> oei = riskPointEvaluationItemDao.findById(entry.getKey());
//                Map<Long, Long> planMap = entry.getValue();
//                String orgCode = null;
//                Long tenentId = null;
//                if (evaluationItem != null) {
////                    RiskPointEvaluationItem evaluationItem = oei.get();
//                    orgCode = evaluationItem.getOrgCode();
//                    tenentId = evaluationItem.getTenentId();
//                    Integer count = evaluationItem.getControlFailureCount();
//                    if (count == null) {
//                        count = 0;
//                    }
//                    Map<Long, Long> itemUncheckedMap = new HashMap<>();
//                    //评估步骤下如果有未检的排查记录itemId则不重新评估实时等级 否则重新评估实时等级
//                    if (!CollectionUtils.isEmpty(planMap)) {
//                        if (org.apache.commons.lang3.StringUtils.isNotBlank(evaluationItem.getUncheckedRecordItemJson())) {
//                            //uncheckedMap : key 排查计划id value 最近一次未检记录itemId
//                            itemUncheckedMap = JSON.parseObject(evaluationItem.getUncheckedRecordItemJson(), new TypeReference<Map<Long, Long>>() {
//                            });
//                            if (!CollectionUtils.isEmpty(itemUncheckedMap)) {
//                                for (Map.Entry<Long, Long> planEntry : planMap.entrySet()) {
//                                    //更新排查计划最后一个未检排查记录itemid
//                                    itemUncheckedMap.put(planEntry.getKey(), planEntry.getValue());
//                                }
//                            } else {
//                                //uncheckedMap : key 排查计划id value 最近一次未检记录itemId
//                                itemUncheckedMap = planMap;
//                                count++;
//                                recordVos.add(new RiskItemEvalCountRecordVo("+1", "未检", "taskTimeOutCheck", entry.getKey(), orgCode, tenentId));
//                                buildBatchItemMap(batchItemMap, evaluationItem);
//                            }
//                        } else {
//                            //uncheckedMap : key 排查计划id value 最近一次未检记录itemId
//                            itemUncheckedMap = planMap;
//                            count++;
//                            recordVos.add(new RiskItemEvalCountRecordVo("+1", "未检", "taskTimeOutCheck", entry.getKey(), orgCode, tenentId));
//                            buildBatchItemMap(batchItemMap, evaluationItem);
//                        }
//                        evaluationItem.setUncheckedRecordItemJson(JSON.toJSONString(itemUncheckedMap));
//                        evaluationItem.setControlFailureCount(count);
//                        evaluationItemList.add(evaluationItem);
//                    }
//                }
//            }
//            if (!CollectionUtils.isEmpty(evaluationItemList)) {
//                riskPointEvaluationItemDao.saveAll(evaluationItemList);
//            }
//            //修改风险点实时等级
//            if (!CollectionUtils.isEmpty(batchItemMap)) {
//                batchRecalculatePointRealLevel(batchItemMap);
//            }
//            if (!CollectionUtils.isEmpty(recordVos)) {
//                List<RiskItemEvalCountRecord> records = riskItemEvalCountRecordService.batchCovertRiskItemEvalCountRecord(recordVos);
//                riskItemEvalCountRecordService.saveBatch(records);
//            }
//        }
//        log.info("风险实时值计算-产生未检 convertUnCheckedRealRiskLevel - end");
    }


    private void buildBatchItemMap(Map<Long, List<Long>> batchItemMap, RiskPointEvaluationItem evaluationItem) {
        List<Long> evalIds = batchItemMap.get(evaluationItem.getRiskPointId());
        if (CollectionUtils.isEmpty(evalIds)) {
            evalIds = new ArrayList<>();
            evalIds.add(evaluationItem.getPointEvaluationId());
        } else {
            if (!evalIds.contains(evaluationItem.getPointEvaluationId())) {
                evalIds.add(evaluationItem.getPointEvaluationId());
            }
        }
        batchItemMap.put(evaluationItem.getRiskPointId(), evalIds);
    }

    @Override
    public void convertCheckedRealRiskLevel(Map<Long, List<Long>> itemPlanMap, String url) {
//        log.info("风险等级实时计算- 消除未检convertCheckedRealRiskLevel-start itemPlanMap={} , url ={}", itemPlanMap, url);
//        for (Map.Entry<Long, List<Long>> entry : itemPlanMap.entrySet()) {
//            Optional<RiskPointEvaluationItem> oei = riskPointEvaluationItemDao.findById(entry.getKey());
//            if (oei.isPresent()) {
//                RiskPointEvaluationItem item = oei.get();
//                if (StringUtils.isNotBlank(item.getUncheckedRecordItemJson())) {
//                    Map<Long, Long> uncheckMap = JSON.parseObject(item.getUncheckedRecordItemJson(), new TypeReference<Map<Long, Long>>() {
//                    });
//                    if (!CollectionUtils.isEmpty(uncheckMap)) {
//                        if (!CollectionUtils.isEmpty(uncheckMap)) {
//                            Iterator<Map.Entry<Long, Long>> iterator = uncheckMap.entrySet().iterator();
//                            while (iterator.hasNext()) {
//                                Map.Entry<Long, Long> next = iterator.next();
//                                List<Long> planIds = entry.getValue();
//                                if (!CollectionUtils.isEmpty(planIds) && planIds.contains(next.getKey())) {
//                                    iterator.remove();
//                                }
//                            }
//                        }
//                        //uncheckMap为空->恢复等级
//                        if (CollectionUtils.isEmpty(uncheckMap)) {
//                            item.setUncheckedRecordItemJson(null);
//                            recalculateRealRiskLevel(ControlRiskLevelType.EFFICIENT.getValue(), new RiskItemEvalCountRecordVo("已检", url, entry.getKey()));
//                        } else {
//                            item.setUncheckedRecordItemJson(JSON.toJSONString(uncheckMap));
//                        }
//                        if (item.getControlFailureCount().intValue() < 0) {
//                            log.info("风险等级实时计算- 消除未检convertCheckedRealRiskLevel controlFailureCount 不能小于0 itemId={}", itemPlanMap);
//                            continue;
//                        }
//                        riskPointEvaluationItemDao.save(item);
//                    }
//                }
//            }
//        }
//        log.info("风险等级实时计算- 消除未检convertCheckedRealRiskLevel - end ");
    }

    @Override
    public Integer getMinPointRealRiskLevel(RiskDistrict district) {
        Integer minPointRiskLevel = null;
        if (district != null) {
            minPointRiskLevel = riskPointDao.getMinRealRiskLevel(district.getId());
        }
        return minPointRiskLevel;
    }

    private Integer calculateMinLevel(Integer level1, Integer level2) {
        if (level1 != null && level2 != null) {
            if (level1 < level2) {
                return level1;
            } else {
                return level2;
            }
        } else if (level1 == null && level2 != null) {
            return level2;
        } else if (level1 != null && level2 == null) {
            return level1;
        }
        return null;
    }


    /**
     * 批量计算风险点实时值
     */
    private void batchRecalculatePointRealLevel(Map<Long, List<Long>> batchItemMap) {
        List<RiskDistrict> districts = new ArrayList<>();
        List<RiskPoint> pointList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(batchItemMap)) {
            List<RiskPoint> points = riskPointDao.findByIds(batchItemMap.keySet());
            Map<Long, RiskPoint> pointMap = points.stream().collect(Collectors.toMap(e -> e.getId(), e -> e));
            for (Map.Entry<Long, List<Long>> entry : batchItemMap.entrySet()) {
                RiskPoint point = pointMap.get(entry.getKey());
                List<Long> evalIds = entry.getValue();
                RiskPointEvaluationBusiness lastControl = null;
                lastControl = getLastRiskPointEvaluationBusiness(entry.getKey(), AnalyzeTypeEnum.CONTROLLABLE.getValue());
                if (point != null && lastControl != null && !CollectionUtils.isEmpty(evalIds) && evalIds.contains(lastControl.getId())) {
                    //计算风险点实时值
                    point.setRealTimeRiskLevel(recalculatePointRealRiskLevel(point, lastControl.getId(), null, ControlRiskLevelType.EFFICIENT.getValue()));
                    pointList.add(point);
                    if (point.getRiskDistrict() != null && !districts.contains(point.getRiskDistrict())) {
                        districts.add(point.getRiskDistrict());
                    }
                }
            }
        }
        if (!CollectionUtils.isEmpty(pointList)) {
            riskPointDao.saveAll(pointList);
        }
        if (!CollectionUtils.isEmpty(districts)) {
            batchRecalculateDistrictRealLevel(districts);
        }
    }

    /**
     * 批量计算区域实时值
     */
    private void batchRecalculateDistrictRealLevel(List<RiskDistrict> districts) {
        if (!CollectionUtils.isEmpty(districts)) {
            districts.forEach(district -> {
                Integer minPointRiskLevel = getMinPointRealRiskLevel(district);
                editRealDistrictLevel(district, district.getRealTimeRiskLevel(), minPointRiskLevel, "隐患排查");
            });
        }
    }

}
